Lesson 42/48 ยท ๐ฏ Problem Solving
๐ฏ Problem SolvingLesson 42/48
Phase 6 ยท Problem Solving22 min
Dictionary Problems
Counting, grouping, and lookup, the three superpowers of dicts
Dictionaries are the Swiss Army knife of Python. These three patterns, counting, grouping, and lookup, solve an enormous range of problems.
Pattern 1: Frequency CounterCount how often each item appears. The foundation of many algorithms.
Frequency counterpython
# Count word frequencies
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'apple': 3, 'banana': 2, 'cherry': 1}
# Find top item
most_common = max(counts, key=counts.get)
print(f"Most common: {most_common}") # applePattern 2: GroupingGroup items by a shared property.
Grouping patternpython
# Group words by their first letter
words = ["apple", "ant", "banana", "bear", "cherry"]
groups = {}
for word in words:
key = word[0]
if key not in groups:
groups[key] = []
groups[key].append(word)
print(groups)
# {'a': ['apple', 'ant'], 'b': ['banana', 'bear'], 'c': ['cherry']}Pattern 3: Lookup TablePre-compute results and store them for O(1) access instead of recalculating.
Lookup tablepython
# Instead of recalculating, pre-compute
squares = {n: n**2 for n in range(1, 11)}
print(squares[7]) # 49, instant lookup
print(squares[10]) # 100๐In the Real World...
In log analysis: count requests per endpoint, group errors by type, map IP addresses to hostnames. In infrastructure: map resource IDs to metadata, group instances by region. Dict patterns are everywhere.
๐ฏ
Phase Complete!
Problem Solving
Describe the 6-step problem-solving framework in your own words. Which step do you find hardest? How do you plan to overcome it?
0/500
Practice Exercises
0/3 solvedExercise 1 of 3medium
โฑ 00:00Top 3 Errors
Given a list of error messages, find the top 3 most frequent ones.
Given: errors = ["TimeoutError", "ConnectionError", "TimeoutError", "ValueError", "TimeoutError", "ConnectionError", "ValueError", "ValueError", "IndexError"]
Expected output:
Given: errors = ["TimeoutError", "ConnectionError", "TimeoutError", "ValueError", "TimeoutError", "ConnectionError", "ValueError", "ValueError", "IndexError"]
Expected output:
TimeoutError: 3ValueError: 3ConnectionError: 2solution.py
1 / 3
Exercise 2 of 3medium
โฑ 00:00Group by Length
Group words by their length.
Given: words = ["hi", "cat", "dog", "it", "elephant", "bee"]Expected output:
Given: words = ["hi", "cat", "dog", "it", "elephant", "bee"]Expected output:
2: ['hi', 'it']3: ['cat', 'dog', 'bee']8: ['elephant']solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Two Sum with Lookup
Using a lookup dict, find if any two numbers sum to the target in ONE pass.
Given: nums = [3, 5, 2, 9, 7], target = 12Expected output:
Given: nums = [3, 5, 2, 9, 7], target = 12Expected output:
Found: 5 + 7 = 12solution.py
3 / 3
Solve all 3 exercises to unlock completion