hiphopfrog
hiphopfrog

Reputation: 1

Removing N Elements

How to write a code that returns a list with all elements that occurred N times removed?

I'm trying to write a python function duplicate(elem, N) which returns a copy of the input list with all elements that appeared at least N times removed. The list can't be sorted. For example ((2, 2, 2, 1, 2, 3, 4, 4, 5), 2) would return (1,3,5).

Upvotes: 0

Views: 79

Answers (3)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

Another way to solve your question by using defaultdict (PS: we can also use a normal dicts too if we want it):

from collections import defaultdict


def duplicate(data, n):
    counter = defaultdict(int)
    for elm in data:
        counter[elm] += 1
    return [k for k, v in counter.items() if v < n]


a = (2, 2, 2, 1, 2, 3, 4, 4, 5)
print(duplicate(a, 2))

Output:

[1, 3, 5]

PS: If you want to compare my code and the Python's collections.Counter class code, visit this collections in Python's Github repository. (Spoiler alert, Counter is using a dict not defaultdict)

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54183

You can use collections.Counter

import collections

def duplicate(lst, n):
    counts = collections.Counter(lst)
    keep = {v for v, count in counts.items() if count < n}

    return [el for el in lst if el in keep]

Upvotes: 2

seech
seech

Reputation: 1

I would use a list comprehension here. Assuming elem is your list of values as input.

[x for x in set(elem) if elem.count(x) < 2]

Upvotes: 0

Related Questions