How Can I Write A List Without Duplicate With Only For, If And Boolean
My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method witho
Solution 1:
def distinct(lst):
dlst = []
forvalin lst:
ifval not in dlst:
dlst.append(val)
return dlst
Solution 2:
Is this considered cheating?
>>>distinct = lambda lst: list(set(lst))>>>distinct([1,3,1,2,6])
[1, 2, 3, 6]
>>>distinct(['a','ab','a','ab'])
['a', 'ab']
Solution 3:
If order isn't important, you can cast it to a set
, then back to a list
defdistinct(lst):
returnlist(set(lst))
Solution 4:
If you need to eliminate duplicates AND preserve order you can do this:
def distinct(lst):
seen = set()
for item in lst:
if item notin seen:
yield item
seen.add(item)
a = [1,3,1,2,6]
print(list(distinct(a)))
[1,3,2,6]
b = ['a','ab','a','ab']
print(list(distinct(b)))
['a', 'ab']
See a demo here: https://ideone.com/a2khCg
Solution 5:
There are Excellent Solutions That I Already Applied. But my professor said us that we don't must use the methods of the list. Has anyone else got any more thoughts?
Post a Comment for "How Can I Write A List Without Duplicate With Only For, If And Boolean"