Pattern Recognition
Concepts covered: Iteration
After a few dozen problems, the loops stop being new. Most of them are 1 of 6 shapes, and the sentence that describes a problem usually names its shape in the first few words. Recognizing the shape means the loop's skeleton is written before you think, and the thinking goes into the condition and the values, where it belongs.
| The question starts with | Pattern | Skeleton |
|---|---|---|
| What is the total ... | Accumulate | total = 0, add each item |
| How many ... | Count | count = 0, add 1 when the condition holds |
| What is the largest / smallest ... | Best so far | best = items[0], replace when an item beats it |
| Which items ... | Filter | kept = [], append when the condition holds |
| How many of each ... | Tally | counts = {}, add 1 under the item's key |
| Is there any / find the first ... | Search | loop, and break at the first match |
Accumulate, count, filter
These 3 share a loop and differ in what sits before it and what the body does. The starting value is the answer for an empty list: 0 for a total, 0 for a count, [] for a filter.
total = 0
for price in prices:
total = total + price
count = 0
for price in prices:
if price > 100:
count = count + 1
expensive = []
for price in prices:
if price > 100:
expensive.append(price)Best so far
Finding a largest or smallest value keeps 1 current best and tests it against every item. The current best starts as the first item, which guarantees it came from the list. The comparison direction is the only thing that changes between largest and smallest.
def cheapest(prices: list) -> float:
best = prices[0]
for price in prices:
if price < best:
best = price
return best
print(cheapest([12.5, 4.0, 9.75]))
print(cheapest([7.0]))Output:
4.0 7.0
Tally
A question with 'of each' in it wants a dictionary: the items are keys and the counts are values. The body has to handle a key seen for the first time, because reading a missing key fails, so the pattern checks in before adding.
def tally(sizes: list) -> dict:
counts = {}
for size in sizes:
if size in counts:
counts[size] = counts[size] + 1
else:
counts[size] = 1
return counts
print(tally(["M", "L", "M", "S", "M"]))Output:
{'M': 3, 'L': 1, 'S': 1}The dictionary keeps keys in the order they were first seen, so M comes first with 3, and L and S follow with 1 each. The first M took the else branch and created the key; the next 2 took the if branch and added to it.
Search
A search stops at the first match, and break is what stops it. The result variable starts as a value that means 'not found', so a list with no match still leaves something to return.
def first_over_budget(costs: list, budget: int) -> int:
found = -1
for cost in costs:
if cost > budget:
found = cost
break
return found
print(first_over_budget([30, 45, 80, 95], 50))
print(first_over_budget([30, 45], 50))Output:
80 -1
The loop runs 3 passes for the first call and stops at 80 without looking at 95. The second call finds nothing and returns the -1 it started with, which the caller can test for.
- Chosen by the question's wording
- 'total of' means accumulate
- 'how many' means count
- 'which ones' means filter
- 'of each' means tally
- Chosen by the data
- the exact comparison and its boundary
- the start value for an empty input
- the type of each item being read
- the value that means 'not found'
Practice
A product manager asks: of all the support tickets opened this week, how many came in from each region? Which pattern fits?
- Count: start at 0 and add 1 for each ticket from the region.
- Tally: a dictionary with regions as keys and ticket counts as values.
- Filter: a list of the tickets whose region matches the one asked about.
- Best so far: the single region with the most tickets this week.
Changing 1 character turns cheapest into a function that finds the longest or largest value: price < best becomes price > best. The start value is still the first item, and the assignment inside the if still writes the item into best. With the direction pointing the wrong way, the loop still runs without an error and returns the smallest value. Only a known answer catches that.
About this lesson
This section is part of the Problem Solving: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.