Teaching Kids Programming – Implement the Counter method in Python


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 words
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

The Permanent URL is: Teaching Kids Programming – Implement the Counter method in Python

3 Comments

Leave a Reply