Frequency Counter Practice Problem
This data science coding problem helps you practice Data Structures, frequency counter, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Data Structures.
- Problem ID: 86
- Problem key: 86-frequency-counter
- URL: https://datacrack.app/solve/86-frequency-counter
- Difficulty: easy
- Topic: Data Structures
- Module: Python Fundamentals
Problem Statement
# š§© Frequency Counter
---
### šÆ Goal
Counting frequencies is one of the most common operations in data science: counting word occurrences in NLP, counting category distributions in EDA, counting class imbalances in ML datasets. This problem is the pure Python foundation of `Counter`, `value_counts()`, and `groupby().count()`.
---
### š What Is a Frequency Counter?
A dictionary that maps each unique item to the number of times it appears:
```
["apple", "banana", "apple", "cherry", "banana", "apple"]
ā {"apple": 3, "banana": 2, "cherry": 1}
```
---
### š» Task
Implement `count_frequencies(items)` **without** using `Counter` from the `collections` module.
---
### š„ Input
- `items`: list of items (strings or numbers)
### š¤ Output
- dict mapping each unique item to its count
---
### š§© Starter Code
```python
def count_frequencies(items):
"""
Count how many times each item appears in the list.
Args:
items (list): List of strings or numbers
Returns:
dict: {item: count} for each unique item
"""
counts = {}
for item in items:
# š§ TODO: If item is already in counts, increment its count
# š§ TODO: If item is not in counts, add it with count = 1
pass
return counts
```
---
### š” Example
```python
count_frequencies(["apple", "banana", "apple", "cherry", "banana", "apple"])
# Expected: {"apple": 3, "banana": 2, "cherry": 1}
```
---
### š Key Concepts
- `dict.get(key, default)` ā returns the value or a default if key doesn't exist
- `if key in dict` ā check membership before accessing
- This is exactly what `collections.Counter` and `pd.Series.value_counts()` doStarter Code
def count_frequencies(items):
"""
Count how many times each item appears in the list.
Args:
items (list): List of strings or numbers
Returns:
dict: {item: count} for each unique item
"""
counts = {}
for item in items:
# š§ TODO: If item is already in counts, increment its count
# š§ TODO: If item is not in counts, add it with count = 1
pass
return counts