Lab: fundamental patterns
Three exercises applying find, count, filter, and transform to fresh problems — pick the right pattern and build it from scratch.
- Apply find, count, filter, and transform patterns to solve small problems
- Identify which pattern is appropriate for a given task
- Practise implementing each pattern from a blank slate
Optional lab. Complete each exercise and hit Check. If you get stuck, re-read the relevant lesson — the pattern name in the heading is the hint.
Three problems, each solvable with one or two of the patterns from this module. Before writing any code, ask yourself: does the answer require producing a new list, or a single value? Does it need to see every element, or can it stop early?
Exercise 1 — most common item
This one calls for the count pattern from the first lesson, extended: instead of counting items that match a single condition, you count how many times each distinct item appears, then find the one with the highest count.
Think first. What do you need to track for each unique item? How do you find the winner once you've gathered that information?
Write most_common(items) that returns the item that appears most often in the list. You may assume there is always one clear winner.
most_common(['a','b','a','c','a']) → 'a'Exercise 2 — remove duplicates
This is a filter-style problem with a twist: the condition depends on history (whether you've seen this item before), not just the item's own value. You'll need a second list to remember what you've already collected.
Think first. What do you append to the result? What condition decides whether to append?
Write remove_duplicates(items) that returns a new list with duplicates removed, preserving the original order of first appearances.
remove_duplicates([1,2,1,3,2]) → [1, 2, 3]Exercise 3 — element-wise sum
Two lists, same length. Produce a third list where each element is the sum of the two corresponding elements. This is a transform — but instead of one source list, you have two.
Think first. How do you visit the elements of two lists at the same index simultaneously? What does the transform step produce for each position?
Write zip_sum(a, b) that takes two lists of equal length and returns a new list where each element is the sum of the corresponding elements from a and b.
zip_sum([1,2,3], [4,5,6]) → [5, 7, 9]Done?
Three green checkmarks. You've applied counting, stateful filtering, and positional transformation — all with nothing more than a loop and a list. The intermediate tier builds directly on this foundation: you'll see how a dictionary can replace many of these loops with instant lookups, and how to think about the cost of what you've written.