Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

delete occurrences of an element if it occurs more than n times python

def delete_nth(order, max_e):
    # Get a new list that we will return
    result = []

    # Get a dictionary to count the occurences
    occurrences = {}

    # Loop through all provided numbers
    for n in order:

        # Get the count of the current number, or assign it to 0
        count = occurrences.setdefault(n, 0)

        # If we reached the max occurence for that number, skip it
        if count >= max_e:
            continue

        # Add the current number to the list
        result.append(n)

        # Increase the 
        occurrences[n] += 1

    # We are done, return the list
    return result

assert delete_nth([20,37,20,21], 1) == [20, 37, 21]
assert delete_nth([1, 1, 1, 1], 2) == [1, 1]
assert delete_nth([1, 1, 3, 3, 7, 2, 2, 2, 2], 3) == [1, 1, 3, 3, 7, 2, 2, 2]
assert delete_nth([1, 1, 2, 2], 1) == [1, 2]
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #delete #occurrences #element #occurs #times #python
ADD COMMENT
Topic
Name
3+6 =