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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Create frequency dictionary8freq = {}9for element in arr:10 freq[element] = freq.get(element, 0) + 11112# Display frequency13print("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
Update freq[element] from its prior count plus one.
- 2
Sort freq.items() for numeric key order.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum