Teaching Kids Programming: Videos on Data Structures and Algorithms
The Counter() from collections is a handy method allows us to count the elements and their frequencies in an iterable:
For example:
Counter("abbc") # { "a": 1, "b": 2, "c": 1 }
We can implement this method by going through each element and update their counter in a defaultdict(int)
def Counter(data):
ans = defaultdict(int)
for i in data:
ans[i] += 1
return ans
Time and space complexity is O(N) where N is the size of the input. We need to iterate over the elements once, and we use a hash map aka dictionary to store the frequencies for each unique elements.
We can use .keys() and .values() to get the keys and values respectively.
For example:
Counter("abbc").keys() # ["a", "b", "c"]
Counter("abbc").values() # [1, 2, 1]
–EOF (The Ultimate Computing & Technology Blog) —
255 wordsLast Post: Longest Distinct Sublist via Sliding Window (Two Pointer) Algorithm
Next Post: C/C++ Function to Compute the Next Highest Power of 2 for a 32-bit Integer
here the code on line 2 will be corrected as
for i in data:
Thank you. Fixed.
here the code on line 2 will be corrected as
for i in data: