0

So I have a problem where I need to remove the integers that occur more than n times from the list. This is giving me an error that remove(x) doesn't exist in the list. Help!

def answer1(data, n):
    for i in range(len(data)):
        item = 0
        if data.count(i) > n:
            item = i
            for k in range(len(data)):
                data.remove(item)
    print(data)

data = [1, 2, 3, 1, 1, 2, 2, 3, 4 ,5]
answer1(data, 2)
Prune
  • 76,765
  • 14
  • 60
  • 81

1 Answers1

2

Your code doesn't work properly because you're removing items from your list while iterating on it. This shortens the list, but the loop iterating on it isn't aware of that (because of its internal index counter)

I would use collections.Counter to count the occurrences (good performance, as opposed to count which scans the list at each iteration) then filter the list using a list comprehension (as a bonus, the original input isn't modified)

import collections
def answer1(data, n):
   c = collections.Counter(data)
   return [x for x in data if c[x]<n]

data = [1, 2, 3, 1, 1, 2, 2, 3, 4 ,5]
a = answer1(data, 2)
print(a)

result:

[4, 5]

(and the initial order is preserved)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219