user3185924
user3185924

Reputation: 51

Duplicates in a string in Python

I realize this question has been asked an infinite number of number of times, but I have spin on it. I am attempting to check a list of elements for duplicates and print either of two responses depending on if there are/are not any duplicates.

I do not wish to wish to remove the duplicates, but simply display a unique message for either of two situations: if there are or are not any duplicates within the string.

I have the following script I created, but it prints seven lines. I wish to reduce to it to one sentence. Thanks.

my_list.sort()

for i in range(0,len(my_list)-1):   
    if my_list[i] == my_list[i+1]: 
        duplicates += 1 
    elif duplicates > 0:
        print "There were duplicates found."
    else:
        print "There were no duplicates"

I spent a lot of time on the internet trying to find a solution for my problem before asking the community--I apologize in advance if this a very, very simple problem.

Upvotes: 0

Views: 234

Answers (1)

bgporter
bgporter

Reputation: 36574

Maybe the most straightforward way is to take advantage of the fact that a set will eliminate any duplicates found in the iterable used to create it. If the length of the set of letters in a string is different than the length of the string, there must be at least one duplicate.

>>> def areDupes(s):
...    return len(set(s)) != len(s)
...
>>> areDupes('abcdef')
False
>>> areDupes('abcdeff')
True

Upvotes: 4

Related Questions