Jun-15-2019, 06:18 PM
Hi,
@pooyan89: iterating over an iterable with
Except this, your code would only find duplicates if they follow each other like
Using the solution with
@pooyan89: iterating over an iterable with
for x in range(...)
and than using the index for accessing the item x of the iterable is a BIG anti-pattern. Simply don't do it. Python can directly iterate over iterables using for item ind iterable:
. If you really need the index of item, use enumerate: for index, item in enumerate(iterable):
Except this, your code would only find duplicates if they follow each other like
['foo', 'bar', 'bar', 'spam']
, but not ['bar', 'foo', 'spam', 'bar']
. But the latter is requested in your homework.Using the solution with
set
and the length comparison would be the way to do it, but if you need to use a loop, use a second list, the in-Operator and a comparison of the length:>>> def has_duplicates(iterable): ... other_list = [] ... for item in iterable: ... if item not in other_list: ... other_list.append(item) ... if len(iterable) > len(other_list): ... return True ... else: ... return False ... >>> foo = ['foo', 'bar' 'spam'] >>> bar = ['foo', 'bar', 'bar', 'spam'] >>> spam = ['bar', 'foo', 'spam', 'bar'] >>> has_duplicates(foo) False >>> has_duplicates(bar) True >>> has_duplicates(spam) True >>>Regards, noisefloor