Frequency of Distinct Elements
Print a count for each distinct integer in sorted order with Python. Students combine a frequency dictionary, a set of keys, and numeric ordering for display.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Frequency of distinct elements8freq = {}9for element in arr:10 freq[element] = freq.get(element, 0) + 11112# Display13print("Frequency of distinct elements:")14for element in sorted(set(arr)):15 print(f"{element}: {freq[element]}")
Output
Enter array size: 6 Element 1: 1 Element 2: 2 Element 3: 2 Element 4: 3 Element 5: 2 Element 6: 1 Frequency of distinct elements: 1: 2 2: 3 3: 1
In this one
- Separate distinct display from counts
- Preserve full frequencies
- Order numeric keys
How it works
- 1
Build the frequency dictionary.
- 2
Visit sorted distinct input values.
- 3
Print each key with its stored full count.
Edge cases
Why use a set for display?
Why use a set for display?
Each distinct integer should appear on one row.
Does sorting the set change arr?
Does sorting the set change arr?
No. arr remains in its input order.
What's going on
The counting pass updates freq using get with a zero default. The display pass visits sorted(set(arr)).
The set prevents repeated output rows; sorting gives a predictable ascending value order. freq[element] supplies the full occurrence count, so duplicates are not lost from the statistics. Empty input has no value rows after the heading.
Why use a set for display? Each distinct integer should appear on one row.
Does sorting the set change arr? No. arr remains in its input order.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Where are occurrence counts stored?
Pick an answer to check it.
Question 2
Why use a set for display?
Pick an answer to check it.
Questions people ask
Why use a set for display?
Each distinct integer should appear on one row.
Does sorting the set change arr?
No. arr remains in its input order.
Where are occurrence counts stored?
In freq.
๐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