I need help with a coding challenge that is asking to remove all occurrences of an item within a list that appear more than once. My code only removes one occurrence. It will not remove the item completely.
def solution(data, n):
for x in data:
while data.count(x) > 1:
data.remove(x)
continue
print(data)
solution([1, 2, 2, 3, 3, 4, 5, 5], 1)
expected result: [1, 4]
actual restult: [1, 2, 3, 4, 5]
you can use collections.Counter to count all instances of each element in data
, then print only the relevant ones based on this count:
from collections import Counter
def solution(data, n):
histogram = Counter(data)
print([d for d in data if histogram[d] <= n])
solution([1, 2, 2, 3, 3, 4, 5, 5], 1)
or just use data.count()
directly:
def solution(data, n):
print([d for d in data if data.count(d) <= n])
solution([1, 2, 2, 3, 3, 4, 5, 5], 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With