APDR

Recursion and Dictionaries

Algorithms, Programming, and Data Representation · Module 92313 · Chapter 8

Recursion solves a problem by asking the same function to solve a smaller version, then uses the returned answer. Dictionaries pair keys with values, giving recursive programs a way to remember earlier work and organize data for lookup.

Start from memory

Try each question first. Mark it sure, unsure, or guessed.

  1. What two parts must a recursive function have to avoid calling itself forever?
  2. For fact(4), what calls are made before the first return?
  3. Why does naive recursive Fibonacci repeat work?
  4. What does d[key] do when the key is absent?
  5. Why can a list be a dictionary value but not a dictionary key?
Check the short answers
  1. A base case that returns directly, and a recursive case that moves toward it. §8.1
  2. fact(4) → fact(3) → fact(2) → fact(1); the base call returns first. §8.2
  3. The same smaller Fibonacci values are calculated in many branches. §8.4
  4. It raises KeyError. §8.6
  5. A key must be hashable with a stable hash; a mutable list is not. Values have no such restriction. §8.6

How to use this guide

For each function, cover the code and trace the calls on paper. Write the argument beside each call, mark the base case, and then unwind the returns. For a dictionary, draw one row per key–value pair and update it after every statement.

  1. Day 0: Try the cold start; study §8.1–8.3 and solve practice 1, 4, 7, 10, 13.
  2. Day 1: Rebuild the call traces from memory; study §8.4–8.5 and solve practice 2, 5, 8, 11, 14.
  3. Day 3: Study §8.6–8.8; solve practice 3, 6, 9, 12, 15, 18.
  4. About day 7: Rebuild the derivations and solve practice 16–20 without notes.
  5. About day 14: Work both exam problems in 20 minutes each; answer the “Explain it” questions aloud.
  6. Before the exam: Tick only skills you can demonstrate cold; use missed answer references to choose what to revisit.

When stuck: for recursion, draw the calls going down and the returned values coming back up. For dictionaries, write the exact contents after each update or deletion; do not rely on a vague idea of what the dictionary “remembers”.

How the chapter fits together

Recursion needs a smaller subproblem and a base case. Tracing makes its control flow visible; induction gives a matching correctness argument. Fibonacci shows repeated work and how a dictionary can cache results. The same recursive pattern applies to strings and nested structures, while dictionaries also support frequency analysis.

Measure · reduce the problem

  • Base case + smaller call §8.1

    f(n) → simpler f(…)

    Rests on: the problem statement; the call must solve the same kind of problem.

  • Call stack and progress §8.2

    calls down · returns up

    Rests on: the base case and the changing argument.

Define · establish correctness

  • Induction §8.3

    base · step

    Rests on: each recursive call has a smaller input covered by the induction hypothesis.

  • Fibonacci and memoization §8.4

    fib(n−1) + fib(n−2)

    Rests on: multiple recursive branches; a dictionary stores completed answers.

Derive · apply and store

  • Recursive strings §8.5

    first + inner + last

    Rests on: a string can be reduced by removing its outside characters.

  • Dictionaries §8.6–8.7

    key → value · count[word] += 1

    Rests on: key-based lookup; values can hold counts or cached results.

QuestionTool
What must a recursive call change?Move a well-founded measure toward a base case (§8.1).
Is the recursion correct?Check the base case, then show a correct smaller result yields a correct larger one (§8.3).
Why is Fibonacci slow?Draw the call tree and mark repeated arguments; cache them (§8.4).
How do I retrieve or update a record?Choose a key, then look up, assign, test membership, or delete (§8.6).
How often does each word occur?Increment its count in a frequency dictionary (§8.7).

8.1 The recursive pattern

A loop repeats a block while its condition holds; recursion expresses repetition as a function calling itself on a smaller problem.

In plain words: recursion is a way to solve a problem by reducing it to a simpler instance of the same problem. A base case is small enough to answer directly. A recursive case makes progress toward that base case and combines its answer with the smaller answer.

Multiplication by repeated additionmult(a, 1) = amult(a, b) = a + mult(a, b − 1) for b > 1Read it as: “multiply a by b by adding a to the product of a and one fewer than b”. This version assumes a positive integer b.
def mult(a, b):
    if b == 1:
        return a
    return a + mult(a, b - 1)

For mult(5, 4), the recursive calls ask for mult(5, 3), then mult(5, 2), then the base mult(5, 1). The result returns as 5, 10, 15, then 20.

Worked example · factorial

  1. We need 4!. Use n! = n × (n − 1)!.
  2. Reduce: 4! = 4 × 3!, 3! = 3 × 2!, 2! = 2 × 1!.
  3. Base: 1! = 1, so return to the waiting calls: 2 × 1 = 2, 3 × 2 = 6, 4 × 6 = 24.
  4. Check: 4! = 4 × 3 × 2 × 1 = 24.

Trap: having a base case is not enough if some inputs never reach it. For every recursive call, name the quantity that gets smaller.

Near miss: return n * f(n) is recursive syntax, but the input never gets smaller, so it does not reach a base case. Change the call to f(n - 1) for positive n.

Recall check · §8.1

  1. What are the two jobs of a recursive case?
  2. Why does the multiplication example state that b is positive?
Check these answers
  1. Make progress toward the base case and combine the smaller answer into the current answer.
  2. Its base case is b == 1 and each step subtracts one; the stated domain guarantees it reaches that case.

8.2 Tracing calls and proving progress

The function does not finish when it calls itself; each earlier call waits for its smaller call to return.

In plain words: Each call gets its own scope, or environment, for its parameter values. Calls stack up while the function goes deeper. When a base case returns, control moves back through the waiting calls, each completing its own calculation.

Factorial recurrencefact(1) = 1fact(n) = n × fact(n − 1) for n > 1Read it as: “the factorial of n is n times the factorial of n minus one”. The call stack stores the unfinished multiplications.

Worked trace · fact(4)

  1. Calls descend: fact(4) → fact(3) → fact(2) → fact(1).
  2. fact(1) returns 1.
  3. fact(2) returns 2 × 1 = 2.
  4. fact(3) returns 3 × 2 = 6.
  5. fact(4) returns 4 × 6 = 24.

One variable name such as n can appear in every call. These are separate bindings: n is 4 in the first frame, 3 in the next, and so on. A returned value travels back; the local name does not.

Sign check: state whether you are tracing the descent (calls) or the return (answers). Reversing them is a common source of wrong traces.

Near miss: writing only fact(1) = 1 and fact(4) = 24 skips the calls that justify the result. Include each intermediate input and return.

Recall check · §8.2

  1. In fact(4), which call returns first, and which last?
  2. Do recursive calls share one local n?
Check these answers
  1. fact(1) returns first; the original fact(4) finishes last.
  2. No. Each call has its own scope and binding for n.

8.3 Induction and correctness

A trace shows one run. To reason that the recursive pattern works for every allowed input, match the program to an inductive argument.

In plain words: Mathematical induction proves a claim over a sequence of integer inputs. First prove the smallest case. Then assume the claim for a smaller input and use that assumption to prove it for the next input. Recursive correctness follows the same shape because each call relies on a smaller case.

Induction structureBase: prove P(n0).Step: assume P(k), prove P(k + 1).Read it as: “establish the first case, then show each true case makes the next one true”. The base value n0 must match the problem’s domain.

Worked proof · sum from zero to n

  1. Claim: 0 + 1 + … + n = n(n + 1)2.
  2. Base n = 0: both sides are 0.
  3. Assume the formula holds for k. Then the sum through k + 1 is k(k + 1)2 + (k + 1).
  4. Factor (k + 1): k(k + 1)2 + (k + 1) = (k + 1)(k + 2)2, which is the formula for k + 1.
  5. Therefore it holds for every integer n ≥ 0.

For recursive code, say what the function promises to return. Verify that promise at the base case. Then assume the smaller call returns its promised answer and show the current step transforms it into the right answer.

Trap: the induction hypothesis is for the smaller case k; do not assume the very statement for k + 1 that you are trying to prove.

Near miss: a proof that checks several values such as 0, 1 and 2 is evidence, not a proof for all n. The induction step covers the general next case.

Recall check · §8.3

  1. What are the two parts of an induction proof?
  2. How does this support a recursive function’s correctness?
Check these answers
  1. A base case and a step from an arbitrary smaller case to its successor.
  2. The base call is correct; if the smaller recursive call is correct, the current combination step returns the correct answer.

8.4 Fibonacci and memoization

Some recursive definitions branch into more than one smaller call, so the same subproblem can be solved repeatedly.

In plain words: In the lecture’s rabbit model, the number at month n is the total from the previous month plus the new pairs produced from the count two months earlier. The naive recursive function rebuilds the same earlier counts in many branches. Memoization stores a result after calculating it so later calls can reuse it.

Fibonacci sequence used in the lecturefib(0) = 1 and fib(1) = 1fib(n) = fib(n − 1) + fib(n − 2) for n ≥ 2Read it as: “each later value is the sum of the previous two values”. This lecture indexes the first two values at 0 and 1, both equal to 1.
def fib(n, cache):
    if n in cache:
        return cache[n]
    answer = fib(n - 1, cache) + fib(n - 2, cache)
    cache[n] = answer
    return answer

cache = {0: 1, 1: 1}
print(fib(6, cache))  # 13

Worked example · cache Fibonacci values

  1. Start with {0: 1, 1: 1}; these are the base cases.
  2. To find fib(4), compute fib(3) and fib(2). The first needs fib(2) again.
  3. The first completed fib(2) stores 2. The later call finds it in the dictionary instead of expanding it again.
  4. Then fib(3) = 3 and fib(4) = 5. Check the sequence: 1, 1, 2, 3, 5.

Slides 40–43 report 11,405,773 recursive calls for naive fib(34) and 65 for the cached version, using the slides’ fib(1)=1, fib(2)=2 indexing. This guide uses a 0-based shift, so its call totals differ; compare algorithms only under the same convention. The important lesson is that caching avoids recalculating completed subproblems.

Trap: caching works only if a result depends on the function’s input, not on hidden changing state or side effects. The same key must mean the same answer.

Near miss: calculating answer but never assigning cache[n] leaves every future call to repeat the work. Store before returning.

Recall check · §8.4

  1. Why is naive recursive Fibonacci expensive?
  2. What two actions make the cached version reuse a result?
Check these answers
  1. It recalculates shared subproblems such as fib(2) in several branches.
  2. Look up the argument before calculating; store the result under that argument after calculating.

8.5 Recursion on strings

A recursive input need not be a number. A string can become a smaller string by removing one or more characters.

In plain words: A palindrome reads the same forwards and backwards. After normalizing a phrase by removing punctuation and changing letters to lowercase, strings of length zero or one are palindromes. Otherwise, compare the first and last characters; if they match, check the inside.

Recursive palindrome testis_palindrome(s) = True when len(s) ≤ 1is_palindrome(s) = s[0] == s[−1] and is_palindrome(s[1:−1])Read it as: “the ends match and the inner string is a palindrome”. This rule is applied after normalization.

Worked example · “Able was I, ere I saw Elba”

  1. Normalize to ablewasiereisawelba.
  2. Compare outside characters: a == a. Recurse on blewasiereisawelb.
  3. Continue comparing pairs toward the centre; each pair matches.
  4. The remaining middle is length zero or one, so return True.

A phrase with a mismatched pair returns False immediately; there is no need to inspect the inside. This is a short-circuit and.

Trap: normalize once before the recursive helper. If punctuation is not removed, the comparison may stop at a comma or space.

Near miss: checking only the first and last characters accepts abca. The inside must also pass the recursive test.

Recall check · §8.5

  1. What are the base cases for the normalized palindrome helper?
  2. What must be true before checking the inner substring?
Check these answers
  1. Strings of length zero or one return True.
  2. The first and last characters must match.

8.6 Dictionaries

Parallel lists can store related fields, but every list must stay aligned and every lookup needs an index. A dictionary connects a key directly to its value.

In plain words: A dictionary stores key–value pairs. A key identifies one entry; a value holds its associated information. Keys are unique and must be hashable. Values may repeat and may be mutable, including lists or other dictionaries.

Core operationsd[key] gets the value or raises KeyErrord[key] = value adds or replaces an entrykey in d tests keys · del d[key] removes an entryd.keys() and d.values() give iterable viewsRead it as: “look up the value attached to this key”. Membership checks keys, not values.

Worked example · replace parallel lists

  1. Parallel form: names[i], grades[i], courses[i] must use matching indices.
  2. Dictionary form: grades = {'Joe': 'B', 'John': 'A+'}.
  3. grades['John'] evaluates to 'A+'; 'John' in grades is True.
  4. grades['Katy'] = 'A' adds an entry. del grades['Joe'] removes one.

Keys need to be hashable: their hash must remain stable while they are in the dictionary. Integers, strings and booleans are common keys; a tuple is usable if all its contents are hashable. A list is not hashable and cannot be a key. A float can technically be a key, but exact floating-point equality can make it a poor choice.

Python 3 dictionaries preserve insertion order. Updating an existing key keeps its position; deleting and re-adding it places it at the end. The lecture slide saying there is “no order” describes older Python behavior. Do not rely on order when the task is about key lookup unless the course explicitly asks about iteration order.

Trap: 'A+' in grades asks whether it is a key; use 'A+' in grades.values() to test values.

Near miss: grades['Sylvan'] does not mean “look up if present”; it raises KeyError. Test membership first when absence is expected.

Recall check · §8.6

  1. What does a dictionary’s in operator test?
  2. Can a tuple containing a list be a key?
Check these answers
  1. Whether the object is one of its keys.
  2. No. The tuple is hashable only if every element is hashable.

8.7 Frequency analysis

Once a word can be used as a key, its value can record how many times it has appeared.

In plain words: A frequency dictionary maps each distinct word to its count. Read one word at a time: increment its old count if it exists, otherwise create it with count one. To find the most common words, first find the largest count, then collect every key with that value.

Frequency updatecounts[word] = counts[word] + 1 when the key existscounts[word] = 1 when it does notRead it as: “increment the count for a repeated word; start a new word at one”.
def lyrics_to_frequencies(words):
    counts = {}
    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
    return counts

Worked example · count and find a tie

  1. Input: ['sun', 'rain', 'sun', 'wind', 'rain'].
  2. After the loop: {'sun': 2, 'rain': 2, 'wind': 1}.
  3. The maximum value is 2.
  4. Collect every key whose value is 2: (['sun', 'rain'], 2). Both words tie.

The lecture’s words_often repeatedly finds the current most common words, records them if their count is at least the threshold, and deletes them from the dictionary. Deletion changes the dictionary passed in. If the caller must keep the original counts, make a copy first.

Trap: when several words share the maximum, return all of them. Stopping at the first key loses valid answers.

Near miss: testing if word in counts.values() checks whether the word equals a count; the membership test belongs on dictionary keys.

Recall check · §8.7

  1. How does the count change when a word appears for the third time?
  2. Why might words_often surprise its caller?
Check these answers
  1. Its existing value is incremented from 2 to 3.
  2. It deletes entries from the dictionary it receives, mutating the caller’s object.

8.8 Choosing recursion

Recursion is not automatically the best implementation; it is especially useful when the input naturally contains nested levels.

In plain words: A list may contain another list, which contains another list, with no fixed depth. Recursion can process one level and call itself on each nested level. This is harder to express with a fixed number of loops. For a simple known sequence, iteration may be clearer and use less call-stack space.

Divide and conquerBreak a problem into smaller problems of the same kind.Solve each smaller problem, then combine their answers.Read it as: “reduce, solve, combine”. A recursive call must still make progress and have a base case.

Worked plan · flatten a nested list

  1. Input: [1, [2, [3]], 4].
  2. Base case: an item that is not a list is already one output element.
  3. Recursive case: for each item, append the item itself if it is simple; otherwise append the flattened result of that nested list.
  4. Combine in order to obtain [1, 2, 3, 4].

The lecture’s learning tasks practise this pattern with reverse, sum, product, count, palindrome, maximum, flatten, Fibonacci, merge of sorted lists, and subsets. Each problem needs its own input domain and base case; do not assume one recursive template solves all of them unchanged.

Trap: a recursive algorithm may be intuitive but costly if it solves the same subproblem repeatedly. Draw the call tree or cache shared results.

Near miss: flattening one level of [1, [2, 3]] gives [1, 2, 3], but it fails on [1, [2, [3]]]. The recursive case must handle a nested list at any depth.

Recall check · §8.8

  1. What makes a nested list a natural recursive input?
  2. When can iteration be the simpler choice?
Check these answers
  1. Each list can contain smaller inputs of the same kind, at an arbitrary depth.
  2. When the repeated steps follow a simple sequence with an obvious loop and no naturally nested structure.

Formula map and units

RuleMeaning
recursive functionbase case + smaller call + combination step
fact(1) = 1; fact(n) = n × fact(n − 1)factorial recurrence for positive integer n
fib(0) = fib(1) = 1; fib(n) = fib(n − 1) + fib(n − 2)lecture’s Fibonacci indexing, n ≥ 2
inductionbase case, then arbitrary step to its successor
d[k], d[k] = v, del d[k]lookup, set, delete by key
if word in counts: counts[word] += 1increment an existing frequency

Check every answer: verify that every recursive path reaches a base case; unwind returns in reverse call order; check an induction base and a general step; for dictionaries, track all key–value changes and note whether a function mutates its input.

Derive it cold

  1. Expand mult(5, 4) to its base case and unwind the result. §8.1–8.2
  2. Trace fact(5) with one argument per call frame. §8.2
  3. Prove the sum formula from 0 through n by induction. §8.3
  4. Draw the repeated-call tree for naive fib(5), then show which values a cache stores. §8.4
  5. Reduce “Able was I, ere I saw Elba” to its normalized string and compare matching ends. §8.5
  6. Build a frequency table for ['a', 'b', 'a', 'c', 'b', 'a'] and report all maximum words. §8.7
  7. Write the base and recursive cases for flattening one nested list. §8.8

Explain it

  1. Why must a recursive call solve a smaller instance of the same problem?
  2. Why does each recursive call get its own scope?
  3. Why is the base case necessary even if the recursive step looks correct?
  4. Why does memoization reduce repeated work in Fibonacci?
  5. Why must dictionary keys be hashable while values may be lists?
  6. When should a frequency function return all words tied for the maximum?
  7. When is recursion more natural than iteration?
Show model answers
  1. Progress toward a directly solvable case ensures the process can stop and makes the subproblem simpler. §8.1
  2. Each call has its own parameter bindings and local variables, even when the names are the same. §8.2
  3. Without a directly solved case, calls have no point at which to stop and return a result. §8.1
  4. It records a completed result by input, so later branches reuse it rather than expanding the same subtree again. §8.4
  5. Dictionary lookup relies on a key’s stable hash; mutable values can change because they are stored data, not lookup addresses. §8.6
  6. Whenever two or more keys share the greatest count; they are all most common. §8.7
  7. When the input naturally contains nested instances of itself, such as lists inside lists. §8.8

Mixed practice

Try all 20 problems before opening the answers. The problems mix traces, correctness, and dictionary updates; write intermediate states rather than guessing.

  1. For the lecture’s mult(a, b), expand mult(3, 4). How many calls are made, including the base call?
  2. Trace fact(5) in call order and give its result.
  3. Starting from d = {'x': 2}, apply d['y'] = 4, d['x'] += 1, then del d['y']. What remains?
  4. A recursive function has base case n == 0 but calls f(n) when n > 0. What is wrong?
  5. For the lecture’s sequence with fib(0)=fib(1)=1, calculate fib(5).
  6. After d = {'a': [1]}, is d['a'].append(2) valid? What is the value afterward?
  7. Complete the induction step for 0+…+k+(k+1), assuming 0 + … + k = k(k + 1)2.
  8. Is {[1, 2]: 'pair'} a valid dictionary? Explain.
  9. Normalize “A man, a plan, a canal: Panama!” using only lowercase letters. What string remains?
  10. What does d['missing'] do for d = {}? How can code check first?
  11. For normalized 'abca', at what comparison does the recursive palindrome test stop?
  12. Count ['red', 'blue', 'red', 'green', 'blue']. Which words are most common?
  13. If fib(6) is already stored as 13, what should a memoized call do before making recursive calls?
  14. Can a dictionary have two different keys with the same value? Give a valid example.
  15. What does word in d check: keys or values? Write a check for a value of 3.
  16. Why is flattening an arbitrarily nested list difficult with a fixed number of loops?
  17. In words_often(freqs, 2), the dictionary is {'a': 4, 'b': 2, 'c': 2}. If it removes every current maximum before repeating, what does it return and what remains?
  18. Why can a tuple be a dictionary key only sometimes?
  19. A memoized function reads a changing global variable as well as its argument. Why might its cache give a wrong result?
  20. Write the base case and recursive rule for summing a list using head and tail. State the empty-list answer.
Show worked answers
  1. mult(3,4) → mult(3,3) → mult(3,2) → mult(3,1); the base returns 3, then 6, 9, 12. Four calls. §8.1–8.2
  2. Calls: 5, 4, 3, 2, 1. Returns: 1, 2, 6, 24, 120. §8.2
  3. {'x': 3}. §8.6
  4. The recursive argument never changes, so it never reaches the base case. It must reduce n, for example to n - 1 for non-negative n. §8.1
  5. Values are 1, 1, 2, 3, 5, 8; therefore fib(5)=8. §8.4
  6. Yes. Lists are allowed as values. The value becomes [1, 2]. §8.6
  7. k(k + 1)2 + (k + 1) = (k + 1)(k + 2)2, the proposed formula at k+1. §8.3
  8. No. A list is mutable and unhashable, so Python raises TypeError when it is used as a key. §8.6
  9. amanaplanacanalpanama. §8.5
  10. It raises KeyError. Use if 'missing' in d: before lookup. §8.6
  11. The outer pair a == a matches, then the inner pair b == c fails, so the result is False. §8.5
  12. Counts: red 2, blue 2, green 1. Both red and blue tie at 2. §8.7
  13. Return cache[6] immediately. §8.4
  14. Yes: {'Mina': 'A', 'Noah': 'A'}. Keys are unique; values may repeat. §8.6
  15. It checks keys. Use 3 in d.values() to check values. §8.6
  16. The nesting depth is not fixed; another nested list may appear at any level. Recursion repeats the same operation at each depth. §8.8
  17. It returns (['a'], 4); after deleting a, it returns (['b', 'c'], 2). The dictionary ends empty because all remaining counts meet the threshold. §8.7
  18. A tuple is hashable only when each element is hashable; a tuple containing a list is not. §8.6
  19. The same key could produce different answers as the global changes, so the cached result may no longer match the current state. Cache only when the key captures all relevant inputs and there are no interfering side effects. §8.4
  20. Base: sum of an empty list is 0. Recursive: sum of a non-empty list is its first element plus the sum of the remaining list. §8.8

Exam-style problems

1 · Memoized sequence · 20 minutes

Use the lecture’s indexing: fib(0)=fib(1)=1, and fib(n)=fib(n−1)+fib(n−2) for n≥2.

  1. Write the base and recursive cases. (3 marks)
  2. Trace the uncached calls for fib(4), showing the repeated argument. (4 marks)
  3. Write a memoized function using a dictionary and explain when it reads and writes the cache. (5 marks)
  4. Give the value of fib(6) and list the cache entries produced when starting with keys 0 and 1. (4 marks)
Show worked answer
  1. Base: return 1 for n=0 or n=1. Otherwise return fib(n−1)+fib(n−2). §8.4
  2. fib(4) calls fib(3) and fib(2); fib(3) calls fib(2) and fib(1), so fib(2) repeats. §8.4
  3. Check if n in cache and return cache[n]; otherwise compute both smaller values, assign their sum to cache[n], then return it. §8.1, §8.4, §8.6
  4. Sequence: 1, 1, 2, 3, 5, 8, 13; fib(6)=13. Newly stored keys are 2, 3, 4, 5, 6 with those values. §8.4

2 · Word report · 20 minutes

Given words = ['oak', 'elm', 'oak', 'ash', 'elm', 'oak', 'ash'] and threshold 2:

  1. Build the frequency dictionary. (3 marks)
  2. Write a function that returns every word tied for most common and its count. (4 marks)
  3. Describe how repeatedly removing the current maximum changes the input dictionary. (4 marks)
  4. Explain why the dictionary can store a list as a value but not use a list as a key. (4 marks)
Show worked answer
  1. {'oak': 3, 'elm': 2, 'ash': 2}. §8.7
  2. Set best = max(freqs.values()), then collect each key k with freqs[k] == best; return (words, best). Here result is (['oak'], 3). §8.7
  3. It deletes the selected key or keys from the same object passed by the caller, so after removing oak it contains elm and ash; both then qualify for threshold 2. Make a copy if the original must remain. §8.7
  4. Values are stored data and may be mutable. Keys must be hashable and stable for lookup; lists are mutable and unhashable. §8.6

Slips in the notes

These corrections preserve the lecture’s intended lesson while making the examples accurate for Python 3. Each is checked against the slide text and current language behavior.

  • Slide 13, induction step. The first instruction in the induction-step bullets says to assume the statement for n+1, but the next bullet correctly says to use the assumption for n. The hypothesis must be for n, which is then used to prove n+1. §8.3
  • Slide 19, Fibonacci docstring. The closing quotes in the displayed function are malformed, so the code does not parse as written. The guide uses a valid function definition. §8.4
  • Slide 32, dictionary views. The examples show keys() and values() as lists. In Python 3 they return dynamic view objects, not lists; convert a view with list(...) when a list is needed. §8.6
  • Slide 34, dictionary order. The slide says there is “no order to keys or values.” Python 3.7 and later guarantee insertion order for dictionaries. The lesson here is key-based lookup, not sorting; the guide states the modern rule explicitly. §8.6
  • Slide 34, keys. It says “immutable type” and lists floats and tuples. The exact requirement is hashability: a tuple is valid only if all its elements are hashable, while custom immutable objects may be hashable or not. §8.6
  • Slides 16–19 and 40–42, Fibonacci indexing. The rabbit table and slide 19 use fib(0)=fib(1)=1, while slides 40 and 42 use fib(1)=1, fib(2)=2. These are the same sequence with indices shifted by one. This guide follows the rabbit table’s 0-based convention. §8.4
  • Slide 43, call counts. The slide’s fib(34) totals use the later one-based indexing. With the guide’s 0-based indexing, the totals for the same argument differ; the reliable comparison is that naive recursion repeats subproblems while memoization reuses them. §8.4

Self-check

Tick a skill only in a later session, at least one day after studying, when you can demonstrate it without notes.

Personal study guide based on the supplied “08_recursion_and_dictionaries.pdf” (46 slides, lecture dated 15–16 November 2025; the slides credit MIT OpenCourseWare 6.0001), written in my own words; no lecture pages or figures are reproduced. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).