Frequency Array

Create frequency array showing count of each element.

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 2: 2
Element 3: 3
Element 4: 2
Element 5: 1
Frequency:
1: 2
2: 3
3: 1

What's going on

Count occurrences of each element.

Key Concepts:

Use dictionary to count
freq.get(element, 0) returns count or 0
Increment count for each occurrence