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:
1 | Counter("abbc") # { "a": 1, "b": 2, "c": 1 } |
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)
1 2 3 4 5 | def Counter(data): ans = defaultdict(int) for i in data: ans[i] += 1 return ans |
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:
1 2 | Counter("abbc").keys() # ["a", "b", "c"] Counter("abbc").values() # [1, 2, 1] |
Counter("abbc").keys() # ["a", "b", "c"] Counter("abbc").values() # [1, 2, 1]
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
272 wordsloading...
Last 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: