CodeBlanks Logo Icon CodeBlanks

Challenge 4

Compute a factorial recursively and print it.

Challenge 4: Hash table counter

In this challenge you will count the frequency of elements in an array using a hash table (dict).

Array: [1, 2, 2, 3, 3, 3]. Result: {1: 1, 2: 2, 3: 3}. Count each element in a dict.

Practice Count frequency

Write count_freq(arr). Count each element's frequency with a dict, print the most frequent. Call count_freq([1,2,2,3,3,3]) to print 3.

Starter code

solution.py
def count_freq(arr):
    # Count frequency

Sample solution

solution.py
def count_freq(arr):
    # Count frequency
    freq = {}
    for x in arr:
        if x in freq:
            freq[x] = freq[x] + 1
        else:
            freq[x] = 1
    max_key = arr[0]
    for k in freq:
        if freq[k] > freq[max_key]:
            max_key = k
    print(max_key)
count_freq([1, 2, 2, 3, 3, 3])

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which data structure is suitable for counting frequency?

  • Queue
  • Hash table Correct answer
  • Stack
  • Array

Explanation: A hash table is suitable for counting frequency.

2 Challenge 4: match the terms

Term Meaning
dict Key-value
frequency Count
count Increment
for Traverse

All lessons in Beginner