newbie_in_python
newbie_in_python

Reputation: 15

Screening for duplicates in a tuple - Python

I am trying to create a function, non_duplicates(), that screens for duplicates for a given tuple x, and returns False if there is a duplicate, or returns True if there isn't any.

I am doing this by a for loop nested within another to iterate over the items twice to compare all the items with each other. I added a conditional that checks if the two items are equal, while their indices are not.

The problem is that the code is giving an equal index for different items for some reason, where I made sure that the index is linked with the iteration.

The answer for non_duplicates(((0,0),(0,0))) is the same as non_duplicates(((0,0),(5,5))), both are giving True while it should not for the former.

When I checked ((0,0),(0,0)), the indices are "0,0 0,0 0,0 0,0", while for ((0,0),(5,5)), the indices are "0,0 0,1 1,0 1,1".

That is why the condition are not being met.

def non_duplicates(x):
    y = 0
    for i, j in x:
        x1 = (i,j)
        for k, l in x:
            x2 = (k,l)
            if (x1 == x2 and x.index(x1) != x.index(x2)):
                y = y + 1
    y = y/len(x)
    if y == 0:
        answer = True
    if y > 0:
        answer = False
    return answer

Upvotes: 1

Views: 218

Answers (2)

Axe319
Axe319

Reputation: 4365

Here is an answer that uses the same logic as @Matt Shin's answer but also works for a tuple of tuples like your example show's you checking.

def non_duplicates(x):
    sorted_tuples = []
    for item in x:
        # sort every tuple in a tuple of tuples and returns a list of sorted tuples
        sorted_tuples.append(tuple(sorted(item)))

    # checks for duplicates using set
    return len(set(sorted_tuples)) == len(sorted_tuples)

print(non_duplicates(((0,0),(0,0))))

print(non_duplicates(((0,0),(5,5))))

Or if your tuple of tuples is really large and you care deeply about computation time. You could check after every element you add.

def non_duplicates(x):
    sorted_tuples = set()
    for count, item in enumerate(x, 1):
        sorted_tuples.add(tuple(sorted(item)))
        if len(sorted_tuples) != count:
            return False

    return True

Upvotes: 0

Matt Shin
Matt Shin

Reputation: 434

If I understand the question correctly, you can try:

def non_duplicates(x):
    return len(set(x)) == len(x)

Upvotes: 1

Related Questions