Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of item(s) in list if it appears more than once

Tags:

python

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]

like image 575
Andrew Avatar asked Sep 18 '25 09:09

Andrew


1 Answers

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)
like image 108
Adam.Er8 Avatar answered Sep 21 '25 00:09

Adam.Er8