Computational
Thinking 8
Finding the items two lists share, first by brute force and then with a cursor over sorted lists; what a side effect is and how a working copy avoids one; and deleting a dictionary key with and without a side effect.
Chapters
Finding Overlaps: the Brute-Force Way
FindOverlap compares every pair: simple, works in any order, costs n × m.
1.1The problem
Say you have two lists and want to know which items show up in both of them. The most straightforward way is to check every item in the first list against every single item in the second list. No assumptions, no shortcuts: just a full comparison.
Procedure FindOverlap(l1, l2)
overlap = []
foreach x in l1 {
foreach y in l2 {
if (x == y) {
overlap = overlap ++ [x]
}
}
}
return(overlap)
End FindOverlapFor every x in l1, the inner loop walks through the entire l2 looking for a match. Whenever one is found, x is appended to overlap. This is the nested foreach from Week 5 (Maths and Physics toppers), now packaged as a procedure.
1.2Example
l1 = [3, 7, 9], l2 = [7, 9, 12]. For 3: no match. For 7: matches 7. For 9: matches 9. Result: overlap = [7, 9].1.3The cost
This works no matter how the lists are ordered, but that generality has a cost. If both lists have n items, you do roughly n × n comparisons in total (in general length(l1) × length(l2)). Fine for small lists, painfully slow for large ones: two lists of 1000 items need 1,000,000 comparisons.
1.4Going deeper
- Order of the result (extra). Matches are appended in the order of
l1. - Repeats (extra). Every matching pair is appended:
FindOverlap([7], [7, 7])gives[7, 7], and so doesFindOverlap([7, 7], [7]). - No side effects. The procedure only reads l1 and l2 and builds a new list.
1.5Exam tips and common mistakes
- Count comparisons as length(l1) × length(l2).
- List matches in the order of l1.
- Stopping the inner loop at the first match: this version does not.
- Thinking the order of the lists matters for correctness here: it does not.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
How many times is x == y checked when l1 has 4 items and l2 has 5?
Every pair.
4 × 5 = 20.- Answer: 20
Multiple Choice Question (MCQ): choose the one correct option.
What does FindOverlap([1, 2, 3], [3, 2]) return?
[3, 2][2, 3][1, 2, 3][]Matches follow l1.
- 2 is found before 3 because l1 is scanned in order.
- Answer: option 2.
Numerical Answer Type (NAT).
What is the length of FindOverlap([7, 7], [7])?
Each x is checked against every y.
- Both 7s of l1 match the 7 of l2:
[7, 7]. - Answer: 2
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about FindOverlap.
Think about order and cost.
- 1, 2 and 4 are true. It works on unsorted lists too (statement 3 is false).
- Answer: options 1, 2 and 4.
Append on a match
1000 × 1000 = 1,000,000
Speeding It Up With Sorted Lists
FindOverlap2: a forward-only cursor over sorted lists, about n + m steps, with a catch.
2.1The idea: a cursor that only moves forward
If both lists are already sorted, we can be smarter. Once we have moved past a value in l2, we never need to look at it again: every later x in l1 is bigger. So instead of rescanning l2 from the top each time, we keep a cursor that only ever moves forward, the same trick used when merging two sorted lists.
first(list) returns the head element. rest(list) returns everything after it: the list minus its head (Week 5).Procedure FindOverlap2(l1, l2)
overlap = []
if (length(l2) == 0) {
return(overlap)
}
else {
y = first(l2)
l2 = rest(l2)
}
foreach x in l1 {
while (y < x and length(l2) > 0) {
y = first(l2)
l2 = rest(l2)
}
if (x == y) {
overlap = overlap ++ [x]
}
}
return(overlap)
End FindOverlap2- If l2 is empty there is nothing to match, so the procedure returns
[]at once. - Otherwise
yholds the current item of l2 andl2holds what is still ahead of it. - For each x, the
whilemoves y forward while it is smaller than x (and items remain). - Then one check
x == ydecides whether x is in the overlap.
2.2Trace on the example
| x | while loop | y | l2 left | x == y? | overlap |
|---|---|---|---|---|---|
| 3 | y = 7 is not < 3: no move | 7 | [9, 12] | no | [] |
| 7 | 7 is not < 7: no move | 7 | [9, 12] | yes | [7] |
| 9 | 7 < 9: move to 9 | 9 | [12] | yes | [7, 9] |
A second run (illustrative): l1 = [2, 4, 6, 8, 10], l2 = [1, 4, 5, 8, 11, 12] gives [4, 8], the same as brute force.
2.3How much faster? (extra)
Each item of l2 is passed by the cursor at most once, and each x gets one equality check, so the work is about length(l1) + length(l2) instead of length(l1) × length(l2).
while condition and every x == y is counted. On the 3-item example that is 7 tests against brute force's 9; on 1000 items, 2,999 against 1,000,000. Both procedures found the same overlap.2.4Only for sorted lists (extra)
The cursor relies on "every later x is bigger". On unsorted lists the procedure can miss matches: FindOverlap2([9, 7], [7, 9]) moves y past 7 while looking for 9, and then never comes back for 7. It returns [9]; the correct overlap is [9, 7].
FindOverlap([7], [7, 7]) gives [7, 7], but FindOverlap2([7], [7, 7]) gives [7], because each x is checked against one y only.2.5The catch
while loop: it reassigns l2 = rest(l2) directly on the parameter that was passed in, not on a copy. By the time the procedure returns, the caller's own list has been chopped down to whatever was left over, even though the caller never touched it. That is a side effect: the procedure silently changed something that lives outside itself.l1 = [3, 7, 9]
l2 = [7, 9, 12]
common = FindOverlap2(l1, l2)
// common is [7, 9], but l2 is now [12]2.6Exam tips and common mistakes
- Trace with columns: x, the moves of y, what is left of l2, the check.
- Always check the precondition: are both lists sorted?
- Using FindOverlap2 on unsorted lists.
- Forgetting the empty-l2 case at the start.
- Assuming the caller's l2 is unchanged afterwards.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
With l1 = [2, 4, 6, 8, 10] and l2 = [1, 4, 5, 8, 11, 12], what does FindOverlap2 return?
[4][2, 4, 8][4, 8][8, 10]Both lists are sorted.
- 4 and 8 are in both lists.
- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
After FindOverlap2([3, 7, 9], l2) with l2 = [7, 9, 12], what is the caller's l2?
[7, 9, 12][12][][9, 12]Follow l2 = rest(l2).
- 7 and 9 were taken off the front; only 12 is left.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does FindOverlap2([9, 7], [7, 9]) return?
[9][7, 9][9, 7][]The cursor never goes back.
- For x = 9 the cursor moves past 7 to 9 and matches; for x = 7 it stays at 9.
- Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about FindOverlap2.
Cost, precondition, side effect.
- 1, 2 and 3 are true. It changes the caller's l2 (statement 4 is false).
- Answer: options 1, 2 and 3.
Moves while y < x
2,999 vs 1,000,000
Unsorted: misses matches
Caller's l2 shrinks
What Is a Side Effect, Really?
A change outside the procedure's own variables; FindOverlap3 avoids it with a working copy.
3.1Definition
Any change a procedure makes to something outside its own local variables: mutating an input list, overwriting a global, printing to the screen. It is not automatically bad, but it turns dangerous the moment it is accidental: the caller has no way of knowing their data changed just from calling something that was supposed to only hand back an answer.
3.2The fix: a working copy
Do not touch the parameter you were handed: make a working copy first, and let only the copy take the damage.
Procedure FindOverlap3(l1, l2)
overlap = []
if (length(l2) == 0) {
return(overlap)
}
else {
myl2 = l2
y = first(myl2)
myl2 = rest(myl2)
}
foreach x in l1 {
while (y < x and length(myl2) > 0) {
y = first(myl2)
myl2 = rest(myl2)
}
if (x == y) {
overlap = overlap ++ [x]
}
}
return(overlap)
End FindOverlap3myl2 = l2 creates a separate working copy that the while loop is free to shrink with rest(), leaving the caller's original l2 completely untouched. Same result as before, minus the surprise.
l1 = [3, 7, 9]
l2 = [7, 9, 12]
common = FindOverlap3(l1, l2)
// common is [7, 9], and l2 is still [7, 9, 12]| FindOverlap | FindOverlap2 | FindOverlap3 | |
|---|---|---|---|
| Needs sorted lists | no | yes | yes |
| Comparisons | about n × m | about n + m | about n + m |
| Changes the caller's l2 | no | yes (accidental) | no |
3.3Links to earlier weeks
- Week 3 (side effects and contracts). A procedure's contract should list its side effects. FindOverlap2's contract would have to say "also empties your l2 up to the last item examined", which no caller wants.
- Weeks 5 and 6 (tables). Procedures that move rows from Table 1 to Table 2 also change something outside themselves; that is why the table must be restored between scans.
3.4Pseudocode and Python (extra)
This course's pseudocode treats a list or dictionary parameter as the caller's own collection, so reassigning it inside the procedure changes what the caller sees, and myl2 = l2 makes a separate copy. Python, used in the other course, behaves differently:
l2 = l2[1:]inside a Python function only rebinds the local name; the caller's list is not changed.- In-place operations do leak:
l2.pop(0),l2.append(x),l2.sort()ordel d[k]change the caller's object. myl2 = l2makes a second name for the same list, not a copy;l2[:]orlist(l2)copies it.
The habit is the same in both: know whether a call can change the data you passed in.
3.5Exam tips and common mistakes
- For any procedure taking a list or dictionary, ask: is the parameter reassigned or changed?
- Copy first, then shrink the copy.
- Calling a side effect "always a bug": it is only a problem when unexpected.
- Shrinking the parameter itself for speed and forgetting the caller.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
Which is a side effect of a procedure?
Outside its own local variables.
- Changing the list it was given affects the caller.
- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
After FindOverlap3([3, 7, 9], l2) with l2 = [7, 9, 12], what is the caller's l2?
[7, 9, 12][12][][9, 12]Only the copy shrinks.
- myl2 is shrunk; l2 is untouched.
- Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Accidental against intended.
- 1, 2 and 4 are true. A side effect is not automatically a bug (statement 3 is false).
- Answer: options 1, 2 and 4.
Dangerous when accidental
Carton finished
Shrink only the copy
pop, append, sort: leak
Deleting a Key: on Purpose
DeleteKey rebuilds the dictionary without k and assigns it back: an intended side effect.
4.1Deleting a key
The same idea shows up with dictionaries. Say you want to delete a key k from a dictionary d. One way: build a fresh dictionary, copy over every key–value pair except the one being deleted, then assign that fresh dictionary back onto d.
Procedure DeleteKey(d, k)
myd = {}
foreach key in keys(d) {
if (k != key) {
myd[key] = d[key]
}
}
d = myd
End DeleteKeychemMarks = {"Rahul":92, "Clarence":73, "Ritika":89}
DeleteKey(chemMarks, "Clarence")
// chemMarks is now {"Rahul":92, "Ritika":89}4.2This time it is intentional
d here is not an accident: it is the whole point of the procedure. Side effects are not always bugs. Sometimes a procedure's entire job is to change something in place, the way deleting a dictionary entry or sorting a list in place naturally works. What matters is that the change is expected, not a surprise.Compare this with FindOverlap2: there, the parameter got mutated as an accidental by-product of an optimisation. Here, mutating the parameter is the purpose; that is the entire reason the procedure exists.
4.3Going deeper
- A key that is not there (extra). If k is not a key, every pair is copied and d ends up with the same contents: deleting a missing key is harmless.
- The cost (extra). Deleting one key copies all the other pairs, so the work grows with the size of the dictionary.
- Why build a new dictionary? The pseudocode has no "remove a key" operation, so the dictionary is rebuilt without it, just as Week 6 rebuilt a list around an inserted item.
4.4Exam tips and common mistakes
- The test is
k != key: copy when the keys differ.
- Writing
k == key, which keeps only the key you meant to delete. - Calling an intended side effect a bug.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
After DeleteKey(chemMarks, "Clarence") on {"Rahul":92, "Clarence":73, "Ritika":89}, what is chemMarks?
{"Rahul":92, "Ritika":89}{"Clarence":73}{}Intended side effect.
- The caller's dictionary loses "Clarence".
- Answer: option 2.
Numerical Answer Type (NAT).
How many keys does chemMarks (3 keys) have after DeleteKey(chemMarks, "Asha")?
"Asha" is not a key.
- Every pair is copied.
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
If the test were k == key instead of k != key, what would DeleteKey(chemMarks, "Clarence") leave?
{"Rahul":92, "Ritika":89}{"Clarence":73}{}Which pairs are copied now?
- Only the pair with key "Clarence" is copied.
- Answer: option 3.
d = myd
Not a surprise
Deleting a Key: Without a Side Effect
DeleteKey2 returns the new dictionary; the caller assigns it, and stays in control.
5.1Hand back the result instead
If you would rather not rely on a side effect at all, write the procedure to simply hand back the new dictionary and let the caller decide what to do with it.
Procedure DeleteKey2(d, k)
myd = {}
foreach key in keys(d) {
if (k != key) {
myd[key] = d[key]
}
}
return(myd)
End DeleteKey2
myd = DeleteKey2(myd, k)Notice the last line: the caller has to explicitly write myd = DeleteKey2(myd, k) to actually use the result. No hidden magic: if that reassignment is not written, nothing changes for the caller, exactly the way an ordinary function call should behave.
chemMarks = {"Rahul":92, "Clarence":73, "Ritika":89}
DeleteKey2(chemMarks, "Clarence")
// result thrown away: chemMarks unchanged
chemMarks = DeleteKey2(chemMarks, "Clarence")
// now chemMarks is {"Rahul":92, "Ritika":89}5.2The contrast
| DeleteKey | DeleteKey2 | |
|---|---|---|
| Ends with | d = myd | return(myd) |
| Caller writes | DeleteKey(d, k) | d = DeleteKey2(d, k) |
| Changes the caller's d | automatically | only if the caller assigns |
| Side effect | yes, intended | none |
DeleteKey mutates automatically and internally. DeleteKey2 stays "pure": it changes nothing on its own and puts the caller fully in control of whether and how the result is used. Week 6's InsertionSort is the same kind: mylist = InsertionSort(mylist).
5.3Exam tips and common mistakes
- For a returning procedure, look for the assignment at the call site.
- Calling DeleteKey2 without assigning the result and expecting d to change.
- Mixing the two: assigning the result of DeleteKey, which returns nothing.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
After the single statement DeleteKey2(chemMarks, "Clarence"), what is chemMarks?
No assignment at the call site.
- The new dictionary is returned and thrown away; chemMarks is unchanged.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
With d the dictionary and k = "Clarence", which statement removes the key from d with DeleteKey2?
DeleteKey2(d, k)k = DeleteKey2(d)d = DeleteKey2(d, k)DeleteKey2 = dAssign the result.
- The caller assigns the returned dictionary back.
- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
mylist = InsertionSort(mylist) follows the DeleteKey2 styleWho decides about the change?
- 1, 2 and 4 are true. DeleteKey returns nothing useful (statement 3 is false).
- Answer: options 1, 2 and 4.
No side effect
Without it: no change
Week 8 Summary Sheet
One page to revise all of Week 8: overlaps, sorted lists, side effects and deleting keys.
Key takeaways
The whole lecture boils down to one habit: knowing exactly when your code is quietly reaching outside itself.
- Watch parameters closely. Reassigning a parameter inside a procedure (like
l2 = rest(l2)) can quietly change the caller's copy too: that is a side effect, whether you meant it or not. - Avoid it with a local copy. If you do not want the caller's data touched, work on a copy (
myl2 = l2) instead of the original parameter. - Sometimes it is the goal. Deleting a dictionary key or sorting a list in place are naturally in-place operations: the side effect there is intended, not a bug.
- Or skip side effects entirely. Return a new collection and let the caller reassign it:
myd = DeleteKey2(myd, k)ormylist=InsertionSort(mylist). - The real skill is not avoiding side effects altogether, but being deliberate about exactly when you use them.
Every time a procedure takes a list or dictionary as input, ask yourself: am I about to change the caller's original, and do I actually want to?
Patterns and how to use them
foreach x in l1 {
foreach y in l2 {
if (x == y) {
overlap = overlap ++ [x]
}
}
}Use whenThe lists are unsorted, or small.
- Loop over l1.
- For each x, scan all of l2.
- Append x on every match.
[3, 7, 9] and [7, 9, 12]: 9 comparisons, [7, 9].foreach x in l1 {
while (y < x and length(myl2) > 0) {
y = first(myl2)
myl2 = rest(myl2)
}
if (x == y) {
overlap = overlap ++ [x]
}
}Use whenBoth lists are sorted and large.
- Copy l2 to myl2 and take its first item as y.
- Move y forward while it is smaller than x.
- Check x == y once per x.
myl2 = l2
y = first(myl2)
myl2 = rest(myl2)Use whenA procedure needs to shrink or change a list it was given, but the caller should not notice.
- Copy the parameter into a local variable.
- Change only the copy.
- Leave the parameter alone.
[7, 9, 12] is still [7, 9, 12].myd = {}
foreach key in keys(d) {
if (k != key) {
myd[key] = d[key]
}
}
d = mydUse whenChanging the caller's dictionary is the purpose of the procedure.
- Copy every pair except k.
- Assign the copy back to d.
- Document the side effect.
{"Rahul":92, "Ritika":89}.d = DeleteKey2(d, k)Use whenYou want no side effects and the caller in control.
- Build and return a new collection.
- The caller assigns it back if wanted.
- Without the assignment nothing changes.
mylist = InsertionSort(mylist) works the same way.The procedures of this week
| Procedure | Needs | Cost | Side effect |
|---|---|---|---|
FindOverlap | any lists | n × m | none |
FindOverlap2 | sorted lists | about n + m | shrinks the caller's l2 (accidental) |
FindOverlap3 | sorted lists | about n + m | none (works on a copy) |
DeleteKey | a dictionary, a key | size of d | changes d (intended) |
DeleteKey2 | a dictionary, a key | size of d | none (returns a new dictionary) |
Common mistakes
- FindOverlap2([9, 7], [7, 9]) misses 7 and returns [9].
l2 = rest(l2)chops the caller's list; usemyl2.
- Deleting a key in place is a side effect by design.
DeleteKey2(d, k)alone changes nothing.
- With repeated values the brute-force and cursor versions can give different counts.
- Rebinding a parameter in Python is local; in-place methods are what leak.