Neural Mastery
← Practice
Count Item Frequencieseasy

Count Item Frequencies

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Implement an element frequency counter using standard Python dictionaries -- the primary foundation for word frequency analysis, token counting, and categorical distribution calculation in machine learning.

Related Skills

Task

Implement count_frequencies(items): return a dictionary mapping each distinct item in items to the number of times it appears. If items is empty, return an empty dictionary {}.

Function Signature

count_frequencies(items: list) -> dict

Examples

Example 1: String Items
Input: items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
Output: {'apple': 3, 'banana': 2, 'orange': 1}
Example 2: Integer Items
Input: items = [1, 2, 2, 3, 3, 3]
Output: {'1': 1, '2': 2, '3': 3}

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must handle empty input list by returning an empty dict {}.
  • Preserves types of the items (strings, integers, etc.) as dictionary keys.
Python3Saved ✓
def count_frequencies(items: list) -> dict:
"""Count the frequency of each element in the input list.

Return a dictionary mapping each unique item to its count.
An empty list should return an empty dictionary."""
# Your implementation here
pass

Case 1: String Items
Input: items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
Expected: {'apple': 3, 'banana': 2, 'orange': 1}
Case 2: Integer Items
Input: items = [1, 2, 2, 3, 3, 3]
Expected: {'1': 1, '2': 2, '3': 3}