Week 5 Exercises — For-Loop Practice
Practice exercises for week 5 (Lecture 5C, “For Loop Practice”), following on from 2025-08-25-for-loops and 2025-08-25-comprehensions. See python-for-loops and python-comprehensions for the reference material needed to solve these.
Q1–Q6 are the week 5 set. Q7–Q11 are the week 4 exercises, from 2025-08-18-while-loops (Lecture 4A) and 2025-08-18-non-primitive-data (Lecture 4B). Q7 is also worked three ways in 2025-08-18-non-primitive-data; it is repeated here because it is the same shape as the rest. Q8–Q11 are worked here, as is the week 4 Caesar cipher (Q3). Every one is a loop over a list, a dictionary or a counter, so they belong in the same practice set. See python-lists, python-dictionaries and python-while-loops for the reference material those need.
On the HTML site, fill in each blank with your answer, then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).
The figures use the palette recorded in csse1001-diagram-notation.
Q1 — Capitalize a string
def capitalize(cs: str) -> str:
""" Capitalize every alphabet letter of a string.
>>> capitalize("boom goes the dynamite!")
'BOOM GOES THE DYNAMITE!'
>>> capitalize("123")
'123'
"""
acc += chr(ord('A') + ord(c) - ord('a'))
Shifting a lower-case letter up to its capital by the fixed gap between 'A' and 'a' in the character encoding.
Q2 — Matrix transpose
def transpose(xss: list[list[int]]) -> list[list[int]]:
""" Return the transpose of xss (rows and columns swapped).
Precondition: xss is square, i.e. len(xss) == len(xss[0]) == ...
>>> transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> transpose([[1]])
[[1]]
"""
Figure 1: Q2 on a \(3\times3\) matrix. A matrix can be represented by a list-of-lists in Python, and indexing it takes two steps — xss[1][-1] is 6, while xss[1,-1] raises TypeError: list indices must be integers or slices, not tuple. Row \(k\) of the result is column \(k\) of the original, which is the whole of the answer. Magenta marks column 1 of xss and the row of the result it becomes.
row = [xs[k] for xs in xss]
Row k of the transpose is column k of the original — the k-th element of every row xs in xss, which is what Figure 1 draws.
Written out with two-step indexing instead of a comprehension, the same row is [xss[i][k] for i in range(len(xss))]. The comprehension form is shorter because xs is xss[i].
Q3 — Caesar cipher
A Caesar cipher shifts each letter a fixed number of places down the alphabet (wrapping around) to encrypt; shifting by the negative amount decrypts it again.
def caesar_cipher(cs: str, shift: int) -> str:
""" Return a string where each character of <cs> has been shifted
by <shift> according to the Caesar cipher.
>>> caesar_cipher("HELLO", 3)
'KHOOR'
>>> caesar_cipher("KHOOR", -3)
'HELLO'
>>> caesar_cipher("abc xyz", 2)
'cde zab'
>>> caesar_cipher("cde zab", -2)
'abc xyz'
"""
The Caesar cipher exercise in 2025-08-18-non-primitive-data asks for separate
encrypt_caeseranddecrypt_caeserfunctions. Same idea here, with a single shift parameter instead of two functions:decrypt_caeser(ct, s)iscaesar_cipher(ct, -s).
acc += chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
% 26 wraps the shift around the alphabet in both directions (including for negative shifts, since Python’s % always returns a non-negative result for a positive divisor).
Q4 — Combine two dictionaries
def combine(d1: dict[int, list[int]], d2: dict[int, list[int]]) -> dict[int, int]:
""" Return the dictionary where each key is a key that is in both
d1 and d2. The value for each key is the sum of all the integers
associated with that key in d1 and d2.
>>> combine({1: [2], 4: [5, 6]}, {4: [8]})
{4: 19}
"""
acc[key] = sum(d1[key]) + sum(d2[key])
The if key in d2 guard is what keeps d2[key] from raising a KeyError. Bare indexing of a missing key raises an error such as KeyError: 'green'. The method alternative, h.get(key), is safer because no error is thrown: it returns None instead.
Q5 — Reverse lookup
def reverse_lookup(d: dict, item) -> list:
""" Returns all keys of <d> such that d[key] == item.
Precondition: the items of <d> are immutable.
>>> reverse_lookup({1: 'bluey', 19: 'chilli', -31: 'bluey'}, 'bluey')
[1, -31]
>>> reverse_lookup({1: 'bluey', 19: 'chilli', -31: 'bluey'}, 'muffin')
[]
"""
A dictionary gives every key one value, but nothing stops two keys sharing a value — which is the only reason this function returns a list. Figure 2 under Q6 draws that.
if d[k] == item:
In CSSE1001 a dictionary is treated as having no ordering, because the keys can be of mixed type. The expected answer [1, -31] nevertheless comes out in the order the keys were written, and [-31, 1] would fail the check above.
A dict iterates in insertion order from Python 3.7 onward. The habit that works either way is not to depend on the order — compare as a set, or sorted(...), when the order is not part of the specification.
Q6 — Invert a dictionary
def invert(d: dict) -> dict:
""" Return the inverted version of d (values become keys, mapping
to a list of the original keys that shared that value).
>>> invert({1: 10, 2: 10})
{10: [1, 2]}
"""
Figure 2: Q5 and Q6 are one picture read in two directions, drawn on Q5’s dictionary. A dictionary is a store of tuple(key, value) pairings found by a hash function. Each arrow is one pairing, which can also be written as a maplet such as \(\texttt{h} \mapsto 1\). A dict gives every key exactly one value, so several keys can land on the same value — 1 and -31 both map to 'bluey'. reverse_lookup follows those arrows backwards for one chosen value; invert reverses all of them at once, which is exactly why the inverted value has to be a list: reversing a many-to-one map gives a one-to-many map. The key order shown is the literal order Q5 writes the dictionary in; nothing should be read into it.
acc[val] = [key]
A one-element list, not the bare key — the if branch above then has something to .append to on the second key that shares this value. Getting this wrong is the usual way Q6 fails: acc[val] = key works for {1: 10} and breaks the moment two keys collide, which is the only interesting case.
This is the same shape as the way of avoiding a KeyError without methods:
if key in table:
table[key] += 1
else:
table[key] = 0
Q6 is the same test with a list in place of a counter. That else branch initialises a new key to 0 rather than 1, which would leave every count one low.
Carry-over: the week-4 exercises
Everything from here on comes from week 4: while-loops (2025-08-18-while-loops, Lecture 4A) and lists and dictionaries (2025-08-18-non-primitive-data, Lecture 4B). Q7 is also worked in 2025-08-18-non-primitive-data. Q8–Q11 are stated in those two notes and worked here.
Q7 — Count occurrences
def count(xs: list[int], ys: list[int]) -> int:
""" Return the number of times members of ys are in xs.
>>> count([1, 2], [1, 2, 3, 4])
2
>>> count([1, 2], [1, 2, 2, 2, 3, 1, 4])
5
"""
Read the specification carefully: the walk is over ys, and xs is only ever asked does it contain this. That is why the second example answers 5 and not 2 — five of the seven members of ys are in xs, counting repeats.
if y in xs:
in is list membership. The whole function can be written three ways.
The while-loop version, walking ys by index:
def count(xs: list[int], ys: list[int]) -> int:
ans, k = 0, 0
while k < len(ys):
y = ys[k]
k += 1
if y in xs:
ans += 1
return ans
The for-loop version. It is certainly better to use a for-loop in this situation.
def count(xs: list[int], ys: list[int]) -> int:
ans = 0
for y in ys:
if y in xs:
ans += 1
return ans
The one-line version.
def count(xs: list[int], ys: list[int]) -> int:
return sum(y in xs for y in ys)
That last one leans on True counting as 1 under sum, and on the generator-expression syntax of 2025-08-25-comprehensions.
Q8 — Rotate a list
def rotate(xs: list, k: int) -> list:
""" Return xs rotated by k.
>>> rotate([0, 1, 2, 3, 4, 5], 2)
[2, 3, 4, 5, 0, 1]
>>> rotate([0, 1, 2, 3, 4, 5], 0)
[0, 1, 2, 3, 4, 5]
"""
The hint is slicing, as in xs[3:6], xs[::2] and xs[7:2:-2].
Figure 3: The rotate exercise solved by slicing. Along the top are the list, the rotation amount and the answer; rotation is defined by that one example and nothing else. Below, the answer: xs[:k] and xs[k:] are the two blocks the list splits into, and rotating is writing them in the other order. Nothing moves within either block, which is why one concatenation of two slices, xs[k:] + xs[:k], is the whole function.
return xs[k:] + xs[:k]
Two slices concatenated, as in Figure 3. The slice bounds need no guarding for k = 0 (xs[0:] is all of it, xs[:0] is empty) and none for k = len(xs) (the other way round), so both ends of the range come out right for free.
The exercise defines rotation by a single example, which leaves two cases unsettled:
klarger than the list.rotate([0, 1, 2], 5)returns[0, 1, 2]unchanged, becausexs[5:]is empty. If a rotation by 5 of a 3-element list should mean a rotation by 2, open withk = k % len(xs). The single example never leaves the range, so it does not say which is wanted.- Negative
k.rotate([0, 1, 2, 3, 4, 5], -1)gives[5, 0, 1, 2, 3, 4]— a rotation the other way. That falls out of Python’s negative-index rule rather than out of any decision, and the example does not say whether it is wanted either.
An index-based alternative, if you want it as a for-loop rather than a slice:
def rotate(xs: list, k: int) -> list:
return [xs[(i + k) % len(xs)] for i in range(len(xs))]
This one does handle k beyond the length, because the % is applied per element.
Q9 — Roll until a six
def roll_until_six() -> int:
""" Print the result of each roll of a six-sided die until a six
is rolled. Return the number of rolls required.
"""
Random number generation is not built in and must be imported:
>>> from random import randint
>>> randint(1, 6) # chosen uniformly over the interval
2
if roll == 6:
The loop is while True for the same reason as the guess-the-number game in 2025-08-18-while-loops: the value the condition needs to test does not exist until the body has run, so there is nothing to put at the top of the loop. The exit is a return, which leaves the function and so the loop outright (break is for the case where there is nothing to hand back).
Because randint is re-rolled every pass, this loop has no bound on how long it runs — only a probability of stopping. That is repeating possibly indefinitely, which is what a while-loop is for, and it is why this cannot be a for-loop.
The rigged die in the cell above is a testing device: rebinding the name randint after the function is defined makes the function pick up the replacement, because Python resolves a global name at call time and not at definition time. Delete those two assignments and the function rolls for real.
Q10 — Accumulate rolls until a threshold
def rolls_to_reach(threshold: int) -> int:
""" Roll a six-sided die, accumulating the results, until the running
total meets or passes <threshold>. Return the number of rolls required.
"""
Q9’s stopping condition looks at the latest roll. This one looks at an accumulator over all of them — the x = x + 1 pattern, which the Python assignment operators let you write as x += 1.
while total < threshold:
Unlike Q9 this loop has a real condition to put at the top, so it needs no while True and no break: total is a genuine accumulator, and the test “have we got there yet” can be asked before the first roll. At the boundary, with threshold = 0, the body never runs at all and the answer is 0 rolls, the same as a while False loop.
The specification says met/passed, so the test must be strict (total < threshold), not total <= threshold: the loop has to stop the moment total reaches the threshold exactly. With the rigged die above the sixth roll takes the total to exactly 20, so a <= here would answer 7 rather than 6 — the boundary is not academic.
Q11 — Addition and multiplication from succ and pred
Two building blocks are given, and the arithmetic has to be built from nothing else:
def succ(x: int) -> int:
return x+1
def pred(x: int) -> int:
return x-1
Develop functions for adding and multiplying positive integers together restricting ourselves to exactly two arithmetic operations:
succ(adding one) andpred(subtract one).
Figure 4: Why the add loop of Q11 is correct and why it stops, traced on add(3, 4). Each pass moves one unit from b across to a, so the total width of the row — the quantity a + b — is the same on every line: it starts at \(3+4\) and ends at \(7+0\), which is why a holds the answer at the moment b reaches 0. The same reading gives termination, since b strictly decreases and cannot go below 0.
total = add(total, a)
add is succ applied b times, and multiply is add applied b times: each function is one loop that walks b down to zero with pred while doing the previous operation once per step. That layering is the point of the exercise — multiplication is repeated addition in the same way addition is repeated succession.
def add(a: int, b: int) -> int:
while b > 0:
a = succ(a)
b = pred(b)
return a
def multiply(a: int, b: int) -> int:
total = 0
while b > 0:
total = add(total, a)
b = pred(b)
return total
Figure 4 is the argument that add is right: a + b is unchanged by the body, so when the loop ends with b == 0 the surviving a is the original a + b. The same trace argues termination — b strictly decreases every pass, so a non-negative b must reach 0.
Both functions read b down to zero and never test a, so the stated precondition matters on one side only: b must be non-negative or the loop never starts and you get a (for add) or 0 (for multiply) back. The exercise says positive integers, so nothing outside that is specified.
Both functions are accumulators driven by a while-loop, which is what makes this a while-loop exercise rather than an arithmetic one.