/frequency_counter.py Secret
Created
May 1, 2021 00:28
Count frequency of items in a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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