Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Frequency Array

Build and display a frequency dictionary for integer list values. Students use get with a default and sort dictionary items for predictable numeric output.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 9 of 10
frequency-array.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Create frequency dictionary
8freq = {}
9for element in arr:
10 freq[element] = freq.get(element, 0) + 1
11
12# Display frequency
13print("Frequency:")
14for element, count in sorted(freq.items()):
15 print(f"{element}: {count}")

Output

Enter array size: 6
Element 1: 1
Element 2: 2
Element 3: 2
Element 4: 3
Element 5: 2
Element 6: 1
Frequency:
1: 2
2: 3
3: 1

In this one

  • Count with a dictionary
  • Supply a missing-key default
  • Sort displayed pairs

How it works

  1. 1

    Update freq[element] from its prior count plus one.

  2. 2

    Sort freq.items() for numeric key order.

  3. 3

    Print one value-count line per key.

Edge cases

What if a value appears once?

What if a value appears once?

Its dictionary count is one.

What if the input is empty?

What if the input is empty?

Only the Frequency heading prints.

What's going on

freq maps each encountered integer to its count. get(element, 0) supplies zero when a key has not yet been stored.

Adding one updates the count for every occurrence. sorted(freq.items()) then orders the key-count pairs by integer key for display. The input list is not sorted or changed; only the output traversal is ordered.

What if a value appears once? Its dictionary count is one.

What if the input is empty? Only the Frequency heading prints.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use a default zero?

Pick an answer to check it.

Question 2

What if a value appears once?

Pick an answer to check it.

Questions people ask

What if a value appears once?

Its dictionary count is one.

What if the input is empty?

Only the Frequency heading prints.

Why use a default zero?

A new key has no previous count.