Problem No 19
Build a frequency dictionary and return the most common item
Hard≈ 24 minute session
Lesson guide
What this Python exercise practices
Build a frequency dictionary and return the most common item is a advanced practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 24 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Advanced
- Estimated time
- 24 minutes
Practice path
Summary
Count how often items appear and return the most frequent one, with a clear tie-breaker.
Problem statement
Write a function most_common_item(items) that takes an iterable (like a list or tuple) of hashable items and returns the item that occurs most frequently. If the iterable is empty, return None. If two or more items have the same highest frequency, return the item among them that appears earliest in the original iterable. Do not use collections.Counter; implement the counting and tie-breaking logic yourself.
Task
Given an iterable of hashable items, build a frequency mapping and return the item with the highest frequency. If multiple items tie, return the one that appears first in the input.
Examples
Basic example
Input
most_common_item([1, 2, 2, 3])
Output
2
Explanation
2 appears twice, more than any other item.
Input format
A single iterable value (e.g., a list) passed as the argument to most_common_item.
Output format
Return the most common item (any hashable type). If input is empty, return None.
Constraints
- Items are hashable (can be used as dictionary keys). - The input may be large but fits in memory. - Do not use collections.Counter; build the frequency mapping manually.
Samples
Sample input 0
most_common_item(['a', 'b', 'a', 'c', 'b', 'a'])
Sample output 0
a
Explanation 0
a appears 3 times, more than any other item.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.