0

I need to create a function that takes two arguments: a list lst and a number num. If an element occurs in lst more than num times, remove the extra occurrence(s) and return the result.

So far I have:

def delete_occurrences(lst, num):
    for x in lst:
        if lst.count(x) > num:
            lst.pop(lst.index(x, lst.index(x)+1))
    return lst

However for an case such as ([1, 1, 3, 3, 7, 2, 2, 2, 2], 3) it doesn't delete the correct repetitions.

4 Answers4

3

IIUC, use list.count with a listcomp to slice the extra-occurrences :

L = [1, 1, 3, 3, 7, 2, 2, 2, 2]

def delete_occurrences(lst, num):
    return [x for i, x in enumerate(lst) if lst[:i+1].count(x) <= num]
​

Output :

delete_occurrences(L, 3)
#[1, 1, 3, 3, 7, 2, 2, 2]
Timeless
  • 22,580
  • 4
  • 12
  • 30
1
def delete_occurrences(lst, num):
    i = 0
    while i < len(lst) :
        if lst.count(lst[i]) > num:
            lst.pop(i)
            i-=1
        i+=1
    return lst
Nehal Birla
  • 142
  • 1
  • 14
1

Here's a solution that keeps your general logic, parsing the list in reverse order so as not to mess up the iteration:

def delete_occurrences(lst, num):
    for i in range(len(lst)-1,-1,-1):
        if lst.count(lst[i]) > num:
            lst.pop(i)
    return lst
Swifty
  • 2,630
  • 2
  • 3
  • 21
0

This works in the way you like:

def delete_occurrences(lst, num):
    element_work_done = []
    for element in lst:
        if lst.count(element) > num and element not in element_work_done:
            elm_indices = [i for i, x in enumerate(lst) if x == element]
            abundant_occurrences = elm_indices[-(lst.count(element)-num):]
            index = 0
            for occurrence in abundant_occurrences:
                lst.pop(occurrence-index)
                index += 1
            element_work_done.append(element)
    return lst

For bigger lists and data samples, this function out-performs other methods for speed of execution by 10x.

RifloSnake
  • 327
  • 1
  • 8