Have I seen the partner?
Many problems ask for pairs: two values that add up to a target, differ by a gap, or mirror each other. Checking every pair is a nested loop. A dict or set turns it into one pass.
For each item, work out the partner it needs. Look the partner up among what you have already seen, then add the item itself:
seen = {}
pairs = 0
for x in values:
pairs += seen.get(7 - x, 0)
seen[x] = seen.get(x, 0) + 1Order matters. Look up before you add, so an item never pairs with itself and each pair is counted once (the later item finds the earlier one).
Store counts, not just presence, when equal values at different positions count as separate pairs.
In the table, watch pairs grow only when a needed partner is already in seen.
See it run
seen = {}
pairs = 0
for x in [2, 5, 3, 2, 5]:
pairs += seen.get(7 - x, 0)
seen[x] = seen.get(x, 0) + 1Count the pairs that add up to 7. Each new value looks for its partner 7 - x among earlier values.
Practice have i seen the partner?
Exercise 1
A gardener records a plant's height in centimetres each week, in heights. The gardener wants to know whether two different weeks have heights that differ by exactly k.
Return True if such a pair of weeks exists and False otherwise.
Rules:
kis at least 1, so a week never pairs with itself and equal heights do not count.- The earlier week may be the taller or the shorter one.
- Fewer than two weeks gives
False.
Constraints: 0 ≤ len(heights) ≤ 10^5; 1 ≤ k ≤ 10^9.
Example: solution([3, 10, 7], 4) returns True because 3 and 7 differ by 4.
Exercise 2
words is a list of lowercase words. A mirror pair is a pair of positions i < j where words[j] is exactly words[i] written backwards.
Return the number of mirror pairs as an integer.
Rules:
- A word that reads the same backwards (like
"aa") mirrors an identical word, so three"aa"words make 3 pairs. - Each pair of positions counts once;
words[i]andwords[j]must be at different positions.
Constraints: 0 ≤ len(words) ≤ 9000; each word has 1 to 8 letters.
Example: solution(["abc", "cba", "xy", "yx", "cba"]) returns 3: (0,1), (0,4) and (2,3).
Exercise 3
A depot has two lists of loads: morning and evening, in kilograms. A match is one load from morning and one load from evening whose weights add up to exactly limit.
Return the number of matches, counted by position: equal weights at different positions are different loads.
Rules:
- A load can appear in many matches.
- Weights can be zero or negative.
- If either list is empty, return
0.
Constraints: 0 ≤ len(morning), len(evening) ≤ 7000; limit is an integer.
Example: solution([2, 2], [3, 3, 3], 5) returns 6 because each of the two 2s matches each of the three 3s.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.