Skip to content

Instantly share code, notes, and snippets.

@tamim
Created May 1, 2021 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamim/c51c29bd2129d17c9c609c2aebf00e41 to your computer and use it in GitHub Desktop.
Save tamim/c51c29bd2129d17c9c609c2aebf00e41 to your computer and use it in GitHub Desktop.
Count frequency of items in a list
from collections import defaultdict, Counter
import random
# using the dictionary data structure
def frequency_counter(li):
freq_dt = dict()
for item in li:
if item in freq_dt:
freq_dt[item] += 1
else:
freq_dt[item] = 1
return freq_dt
# using defaultdict
def frequency_counter(li):
freq_dt = defaultdict(int)
for item in li:
freq_dt[item] += 1
return freq_dt
# using Counter
def frequency_counter(li):
freq_dt = Counter(li)
return freq_dt
if __name__ == "__main__":
li = [2, 6, 9, 2, 8, 2, 9, 9, 3, 1, 4, 5, 7, 1, 8, 10, 2, 10, 10, 5]
freq = frequency_counter(li)
assert freq[1] == 2
assert freq[2] == 4
assert freq[3] == 1
assert freq[11] == 0 # this test will fail when we use dictionary (the first function)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment