1

I know that there are already a lot of questions about this specific topic, but I can't find a proper solution for my problem.

I have the input:

2, 20, 15, 16, 17, 3, 8, 10, 7

I want to see if there are 'double' numbers in my code. I have tried working with this code.

lijst = input('Give a list:  ')
teller = 0
for i in lijst.split(','):
    if lijst.count(i) != 1:
        teller += 1
print(teller != 0)

Normally I should get False, since there are no double numbers in the given list. However, I recieve True. I suggest that's because the 2 appears also in 20.

True

Does anyone know how to avoid this problem, so the the '2' isn't counted twice?

2 Answers 2

2

You can use collections.Counter which does exactly that

>>> data = [2, 20, 15, 16, 17, 3, 8, 10, 7]
>>> from collections import Counter
>>> Counter(data)
Counter({2: 1, 3: 1, 7: 1, 8: 1, 10: 1, 15: 1, 16: 1, 17: 1, 20: 1})
>>> 

It counts number of occurences and returns a dict with keys indicates the item, and value is number of occurences.

If you just need to know if there are duplicates or not, regardless of which item is the duplicate, you can simply use Set over your list and check len() afterwards:

len(data) == len(set(data))

Sign up to request clarification or add additional context in comments.

Comments

1

You can compare the length of the input with the length of the set of unique elements in input:

def has_repeated_elements(input):
    """returns True if input has repeated elements,
    False otherwise"""
    return len(set(input)) != len(input)

print(not has_repeated_elements(input))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.