Reputation: 2919
I have an tuple containing 100 string values (say). Now, I want to check if two string elements there in the tuple are same?
I tried to do something like this with nested loops:
def hasDuplicates(arr: tuple):
ctr = 0
# arr looks something like this & len(arr) == 100
# arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr', ...)
for m in arr:
for n in arr:
if n == m:
ctr += 1
# while looping, len(arr) times every element
# will be compared with itself
if ctr > len(arr):
return True
return False
...which worked but I think there is a better work around for this. Can anyone provide a better solution to this? :)
Upvotes: 1
Views: 8531
Reputation: 7844
You can also check this using any
keyword and count
method from list
object:
arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr')
def sameStrings(arr):
return any(arr.count(elem)>1 for elem in list(arr))
print(sameStrings(arr))
Output:
True
Edit
Updating answer with proposed solution by @timgeb using Counter
from collections
module:
from collections import Counter
arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr')
def sameStrings(arr):
myCounter = Counter(list(arr))
return max(myCounter.values())>1
print(sameStrings(arr))
Output:
True
Upvotes: 2
Reputation: 78730
If I understand correctly, you can just convert your tuple
to a set
and check whether it has the same length as the original tuple.
def has_duplicates(iterable):
l = list(iterable) # in case iterable is an iterator
return len(set(l)) != len(l)
Demo:
>>> tup = ('abc', 'bcd', 'sdf', 'abc', 'pqr')
>>> has_duplicates(tup)
>>> True
>>> has_duplicates(range(100))
>>> False
Won't work for infinite iterators :)
~edit~
A more general version that does not have to build a potentially long list
and set
upfront:
def has_duplicates(iterable):
seen = set()
for x in iterable:
if x in seen:
return True
seen.add(x)
return False
Of course, both versions require the elements of your iterable to be hashable.
Upvotes: 4