Remove All Occurrences Of Item(s) In List If It Appears More Than Once
Solution 1:
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
defsolution(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:
defsolution(data, n):
print([d for d in data if data.count(d) <= n])
solution([1, 2, 2, 3, 3, 4, 5, 5], 1)
Solution 2:
As this is a coding challenge, it might be better to not rely upon Python-specific stuff, like collections
or the count()
function.
You could generically do this in any language using a hash table, which in Python is just a dictionary.
I assume the presence of the parameter n
is to make the threshold above which you remove the number configurable, and not simply hard-coded to 1.
data = [1, 2, 2, 3, 3, 4, 5, 5]
defsolution(data, n):
occurrences = {}
# count occurrencesfor item in data:
occurrences[item] = occurrences.get(item, 0) + 1# return trimmed data
trimmed_data = []
for item in data:
if occurrences[item] <= n:
trimmed_data.append(item)
return trimmed_data
solution(data, 1)
yields
[1, 4]
This has O(n) time complexity.
You can save the second list by re-using the first one:
defsolution(data, n):
occurrences = {}
# count occurrencesfor item in data:
occurrences[item] = occurrences.get(item, 0) + 1# return trimmed data
data.clear()
for k, v in occurrences.items():
if v <= n:
data.append(k)
return data
Solution 3:
You could do:
def solution(data, n):
for x inset(data):
ifdata.count(x) > n:
while x indata:
data.remove(x)
returndata
Some explanation:
set(data)
makes that every value is checked only once, even if it occurs multiple times indata
;- you should remove the
continue
statement, it does not do what you probably want it to do; - look carefully what I am doing with the
if
statement and thewhile
statement; - in your code, the
n
argument was not used, I assumed that it should replace the1
in theif
-line.
Update: Here is the one line version!
solution = lambda data, n: [x for x inset(data) ifdata.count(x) <= n]
You can call the solution function the same as before. If you are puzzled about this syntax, you could search 'python list comprehensions' and 'python lambda'.
Post a Comment for "Remove All Occurrences Of Item(s) In List If It Appears More Than Once"