10.2. Functional Practice#

This section applies the ideas from Functional Programming to three techniques you can use in larger programs. Recursion repeats work without a mutating loop counter, so it fits nested data. Context managers guarantee setup and cleanup around a block, and @contextmanager is itself a decorator that wraps a generator function. The functools module collects higher-order functions: reduce() combines many values into one, partial() fixes some arguments in advance, and lru_cache() remembers results so that repeated calls are not recomputed.

10.2.1. Recursion#

Recursion is taught in 4.3 Recursion: a base case stops the calls, and a recursive case calls the function on a smaller problem. Recursion suits functional programming because a recursive function repeats work without mutating a loop counter. This section compares recursion with iteration, and the lru_cache() example later in this notebook caches a recursive function.

Recursion fits data that contains smaller copies of itself. A folder holds files and other folders, so a function that prints a folder can call itself on each subfolder. A file is the base case: it has no children, so the function prints it and stops. The example builds a small sample tree in a temporary folder, which is deleted when the with block ends.

# Tree traversal: the same function handles every level of the folder tree
import os
import tempfile

def print_directory(path, level=0):
    """Print a folder and everything inside it, indented by depth."""
    print('  ' * level + os.path.basename(path))
    if os.path.isdir(path):                         # a file is the base case: nothing more to visit
        for item in sorted(os.listdir(path)):       # recursive case: visit each child one level deeper
            print_directory(os.path.join(path, item), level + 1)

# Build a small sample tree in a temporary folder
with tempfile.TemporaryDirectory() as root:
    project = os.path.join(root, 'project')
    for folder in ['data', 'src/utils']:
        os.makedirs(os.path.join(project, folder))
    for name in ['README.md', 'data/sales.csv', 'src/main.py', 'src/utils/helpers.py']:
        open(os.path.join(project, name), 'w').close()

    print_directory(project)
project
  README.md
  data
    sales.csv
  src
    main.py
    utils
      helpers.py

The folder example only prints. Many recursive functions instead return a value, and the recursive case uses the value that the smaller call returns. A factorial shows the pattern: n! = n * (n - 1)!, and 0! = 1 is the base case.

Reading the calls from the top, each call waits for the call below it. Once the base case returns, the waiting calls finish in reverse order:

factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * (1 * factorial(0))))
= 4 * (3 * (2 * (1 * 1)))      # base case reached: factorial(0) returns 1
= 24

Digits give a second pattern for shrinking a problem. For a positive integer, n // 10 removes the last digit and n % 10 is the last digit. The function count_digits below uses n // 10 as the smaller problem and counts one digit for each call.

def factorial(n):
    if n == 0:                      # base case: stop here
        return 1
    return n * factorial(n - 1)     # recursive case: multiply by the smaller answer

def count_digits(n):
    if n < 10:                      # base case: a single digit
        return 1
    return 1 + count_digits(n // 10)    # drop the last digit, count it as 1

print(factorial(4))         # 24
print(count_digits(1234))   # 4
24
4

10.2.1.1. Recursion vs Iteration#

Advantages of recursion:

  • Elegant and intuitive for certain problems

  • Mirrors mathematical definitions

  • Good for tree/graph traversal

Disadvantages:

  • Can be slower due to function call overhead

  • Risk of stack overflow with deep recursion

  • May use more memory

Python recursion limit: Python has a default recursion limit (usually 1000). You can check it with sys.getrecursionlimit().

The same function can be written both ways. The recursive version follows the mathematical definition. The iterative version keeps a running product in a loop variable:

def factorial_recursive(n):
    if n == 0:
        return 1
    return n * factorial_recursive(n - 1)

def factorial_iterative(n):
    result = 1
    for k in range(2, n + 1):       # mutates result and k: the imperative style
        result *= k
    return result

print(factorial_recursive(10), factorial_iterative(10))     # 3628800 3628800
3628800 3628800

Both give the same answer, so the choice is about fit. Each recursive call adds a frame to the call stack and the loop does not, which is why recursion costs more memory and time per step. The cost becomes visible when the depth is large. A recursive call that goes deeper than the limit raises RecursionError, while the loop handles the same input without trouble:

import sys

print(sys.getrecursionlimit())      # 1000 by default

try:
    factorial_recursive(5000)       # needs 5000 nested calls
except RecursionError as error:
    print("RecursionError:", error)

print(factorial_iterative(5000).bit_length())       # the loop handles it: 5000! needs 54233 bits
1000
RecursionError: maximum recursion depth exceeded
54233

Use recursion when the data is itself nested, such as folders or trees, because the code mirrors the structure. Use a loop when you are repeating a step over a long sequence.

10.2.1.2. Recursion on Nested Data#

Folders are one nested structure. A list that contains other lists is another, and its depth is not fixed: [1, [2, [3]]] has three levels, while [1, 2] has one. A loop over the list reaches only the first level, so a nested loop would need one more for for every level of nesting. Recursion handles any depth with one function, if the function does two things:

  1. Recognize the base case. An item that is not a list has no inside to explore. isinstance(data, list) returns True when data is a list, so not isinstance(data, list) identifies the base case.

  2. Combine the answers of several smaller calls. A list holds many items, so the recursive case calls the function once for each item and combines the returned values. The factorial example made one recursive call per step. A list makes one call per element, and the results must be combined, here with max().

The function depth returns how many levels of lists a value contains. A number contains no list (depth 0). A list is one level deeper than its deepest element.

def depth(data):
    if not isinstance(data, list):      # base case: a number has no list inside
        return 0
    deepest = 0
    for item in data:                   # recursive case: ask about each element
        deepest = max(deepest, depth(item))
    return 1 + deepest                  # this list adds one level to its deepest element

print(depth(5))                 # 0
print(depth([]))                # 1: an empty list is one level with nothing inside
print(depth([1, 2]))            # 1
print(depth([1, [2, [3]]]))     # 3
0
1
1
3

Trace depth([1, [2, [3]]]). The outer list asks about 1 (depth 0) and about [2, [3]]. That list asks about 2 (depth 0) and about [3], which asks about 3 (depth 0) and returns 1 + 0 = 1. The middle list returns 1 + 1 = 2, and the outer list returns 1 + 2 = 3. As with factorial, the answers come back from the base case outward.

10.2.1.3. Practice#

10.2.1.3.1. Count Down#

### Exercise: Count Down
#   Write `count_down(n)` that prints n, n-1, ..., 1, then "Blastoff!".
#   Base case: n <= 0 -> print "Blastoff!" and return.
#   Recursive case: print n, then call count_down(n - 1).
#   Call count_down(3). Expected output: 3, 2, 1, Blastoff! on separate lines.
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
def count_down(n):
    if n <= 0:
        print("Blastoff!")
    else:
        print(n)
        count_down(n - 1)

count_down(3)
3
2
1
Blastoff!

10.2.1.3.2. Sum Digits#

### Exercise: Sum Digits
#   Write `sum_digits(n)` that returns the sum of the digits of a positive integer.
#   Base case: n < 10 -> return n.
#   Recursive case: add the last digit (n % 10) to sum_digits of the rest of the number (n // 10).
#   Print sum_digits(1234) and sum_digits(99). Expected output: 10 and then 18.
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
def sum_digits(n):
    if n < 10:
        return n
    return n % 10 + sum_digits(n // 10)

print(sum_digits(1234))  # 10
print(sum_digits(99))    # 18
10
18

10.2.1.3.3. Nested Data#

### Exercise: Nested Data
#   A nested list holds numbers and other lists, like a folder holds files and folders.
#   Unlike the first two tasks, this data has no fixed depth, so a fixed set of nested loops cannot reach every level.
#   1. Write `total_items(data)` that returns how many numbers the nested list holds.
#      Base case: an item that is not a list counts as 1 (test it with isinstance(item, list)).
#      Recursive case: for a list, add up total_items() of each element in it.
#   2. Print total_items(basket).
#   3. Count the items with a single loop over `basket` alone (no recursion), and print that count
#      to see what the loop misses.
#   Print exactly:
#   7
#   3
basket = [3, [5, 8], [[2], 4, [1, 6]]]
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
basket = [3, [5, 8], [[2], 4, [1, 6]]]

def total_items(data):
    if not isinstance(data, list):      # base case: a single number
        return 1
    total = 0
    for item in data:                   # recursive case: add up each element
        total += total_items(item)
    return total

print(total_items(basket))              # 7

count = 0
for item in basket:
    count += 1
print(count)                            # 3
# A loop over basket alone counts [5, 8] and [[2], 4, [1, 6]] as one item each,
# because it does not look inside the nested lists.
7
3

10.2.1.3.4. Recursion or Loop#

### Exercise: Recursion or Loop
#   Write `sum_to` two ways. Each version returns 1 + 2 + ... + n for n >= 0.
#   1. `sum_to_recursive(n)`: base case n == 0 returns 0; otherwise n + sum_to_recursive(n - 1).
#   2. `sum_to_iterative(n)`: a for loop over range(1, n + 1) with a running total.
#   3. Print both results for n = 10, on one line.
#   4. Call sum_to_recursive(5000) inside try/except RecursionError and print "RecursionError"
#      when it fails. Then print sum_to_iterative(5000).
#   5. Decide which version suits a sequence of 100000 values, and print
#      "Use for 100000 values: " followed by "recursive" or "iterative".
#   Print exactly:
#   55 55
#   RecursionError
#   12502500
#   Use for 100000 values: iterative
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
def sum_to_recursive(n):
    if n == 0:
        return 0
    return n + sum_to_recursive(n - 1)

def sum_to_iterative(n):
    total = 0
    for k in range(1, n + 1):
        total += k
    return total

print(sum_to_recursive(10), sum_to_iterative(10))       # 55 55
try:
    print(sum_to_recursive(5000))
except RecursionError:
    print("RecursionError")                             # 5000 nested calls exceed the default limit
print(sum_to_iterative(5000))                           # 12502500
# Use the loop for 100000 values: the sequence is flat, so recursion adds a stack frame
# per value for no benefit and would exceed the recursion limit.
print("Use for 100000 values: iterative")
55 55
RecursionError
12502500
Use for 100000 values: iterative

10.2.2. Context Managers#

A context manager is a special Python object designed to automate the allocation and release of system resources. It ensures that setup actions (such as opening a file or acquiring a lock) and cleanup actions (such as closing the file or releasing the lock) are performed reliably, even if errors occur during execution.

Specifically, context managers are objects that define what happens at the start and end of a with statement. They ensure proper resource management and cleanup, even if an exception occurs.

They connect back to functional programming here because @contextmanager is itself a decorator: a higher-order function that transforms a generator function into a context manager.

To see what a context manager saves you from, write the cleanup by hand. A try/finally block runs its finally clause on every path out of the block, including an exception, so it is the pattern that a with statement packages. The familiar with open(path) as f: closes the file the same way, however the block ends.

# By hand: you must remember the cleanup on every path
print("Open report")
try:
    print("Writing report")
finally:
    print("Close report")         # runs even if the block above raises
Open report
Writing report
Close report

This works, but every place that uses the resource must repeat the try/finally. A context manager writes the setup and cleanup once, and each use becomes a with statement.

The @contextmanager decorator from contextlib turns a function that contains yield into a context manager. The function runs in three parts:

  • Setup. When the with statement starts, the code before yield runs.

  • Pause. At yield, the function pauses and hands the yielded value to the with block, which binds it to the name after as. The body of the with block then runs.

  • Cleanup. When the with block ends, the function resumes after yield. Put the cleanup code in a finally clause around the yield, so it runs even if the with block raises an exception.

In the timer() example below, the setup records the start time, yield start_time binds that value to start, and the finally clause prints the elapsed time.

A function that pauses at yield is called a generator function. This section uses yield only inside @contextmanager; 11.2 Generators covers yield and generator functions fully.

# Creating context managers using contextlib
from contextlib import contextmanager
import time

@contextmanager
def timer():
    start_time = time.perf_counter()
    print("Timer started")
    try:
        yield start_time
    finally:
        end_time = time.perf_counter()
        print(f"Timer finished: {end_time - start_time:.4f} seconds")

# Using the timer context manager
with timer() as start:
    time.sleep(0.1)  # Simulate some work
    print(f"Work started at: {start}")
Timer started
Work started at: 141.89214489
Timer finished: 0.1003 seconds

The finally clause matters most when something goes wrong. In the next example, the second with block raises a ValueError. The context manager prints its cleanup line first, and then the exception keeps traveling outward to the try/except that surrounds the with statement. The context manager does not hide the error; it only guarantees that the cleanup code runs.

from contextlib import contextmanager

@contextmanager
def opened(name):
    print(f"Open {name}")         # setup: runs when the with block starts
    try:
        yield name.upper()        # pause: this value is bound by `as`
    finally:
        print(f"Close {name}")    # cleanup: runs even if the block raises

# A block that finishes normally
with opened("sales") as label:
    print(f"Reading {label}")

# A block that raises: cleanup runs, then the error reaches the outer except
try:
    with opened("orders") as label:
        print(f"Reading {label}")
        raise ValueError("bad record")
except ValueError as error:
    print(f"Caught: {error}")
Open sales
Reading SALES
Close sales
Open orders
Reading ORDERS
Close orders
Caught: bad record

Context managers can be nested. Cleanup runs in the reverse order of setup, like the unwinding of the recursive calls above. Predict the output of the next cell before you run it: in what order do the four tag lines and the word text print?

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    try:
        yield
    finally:
        print(f"</{name}>")

with tag("outer"):
    with tag("inner"):
        print("text")
<outer>
<inner>
text
</inner>
</outer>

The output is <outer>, <inner>, text, </inner>, </outer>. The inner block is entered last, so it is cleaned up first.

### Exercise: Context Managers
#   1. Write a context manager `section(title)` with @contextmanager.
#      On entry it prints "=== title ===". On exit it prints "=== end title ===".
#      Use try/finally so the closing line always prints.
#   2. Use `section("Load")` in a with block that prints "Reading data" and then
#      raises KeyError("missing"). Wrap the with statement in try/except KeyError and
#      print "Caught: ..." in the except clause.
#      Check the order of the printed lines: the closing line must come before "Caught".
from contextlib import contextmanager

### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
from contextlib import contextmanager

@contextmanager
def section(title):
    print(f"=== {title} ===")
    try:
        yield
    finally:
        print(f"=== end {title} ===")

try:
    with section("Load"):
        print("Reading data")
        raise KeyError("missing")
except KeyError as error:
    print(f"Caught: {error}")
# === Load ===
# Reading data
# === end Load ===
# Caught: 'missing'
=== Load ===
Reading data
=== end Load ===
Caught: 'missing'

10.2.3. The functools Module#

The functools module provides higher-order functions that operate on or return other functions. Three particularly useful tools are reduce, partial, and lru_cache. Each answers a different question: how do I combine many values into one (reduce), how do I fix some arguments of a function in advance (partial), and how do I avoid repeating an expensive call (lru_cache).

10.2.3.1. functools.reduce()#

You met reduce() and its initializer in Functional Programming. Think of it as a fold: it combines the items left to right into one accumulated value.

The accumulated value does not have to be a number. In the example below, the accumulator is a list, so acc + x concatenates lists and reduce() flattens a list of lists. The initializer [] gives the fold an empty list to start from.

from functools import reduce

# Flatten a list of lists: the accumulator is a list, so + concatenates
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda acc, x: acc + x, nested, [])
print(flat)     # [1, 2, 3, 4, 5, 6]

# In practice, prefer a nested comprehension for flattening; it reads more clearly.
print([item for group in nested for item in group])
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

10.2.3.2. functools.partial()#

partial(function, *args, **kwargs) returns a new function with some arguments pre-filled. This is called partial application — useful for creating specialized versions of general-purpose functions.

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)     # exponent is fixed by keyword
cube   = partial(power, exponent=3)

print(square(4))   # 16
print(cube(3))     # 27

# Practical: pre-configure print with a separator
header = partial(print, sep=' | ')
header('Name', 'Score', 'Grade')  # Name | Score | Grade
16
27
Name | Score | Grade

partial can fix arguments by keyword, as above, or by position. Positional arguments fill the parameters from the left, in order. A partial is like a small lambda that forwards its remaining arguments, so partial(add, 10) behaves like lambda b: add(10, b):

def add(a, b):
    return a + b

add10 = partial(add, 10)        # 10 fills a, the first parameter
print(add10(5))                 # 15

# Common mistake: a positional value fills the FIRST parameter
power_of_2 = partial(power, 2)  # base=2, not exponent=2
print(power_of_2(5))            # 32, which is 2 ** 5; square(5) would give 25
15
32
### Exercise: reduce and partial
#   1. Use reduce() to build the maximum of nums as a fold, to see how folding works,
#      and print it. (Hint: lambda acc, x: acc if acc > x else x)
#      Then print the same maximum with the built-in you would use for this in real code.
#   2. Use partial() to create `add10`, a function that adds 10 to any number.
#      Print add10(5) and add10(-3).
#   3. Specialize meets_minimum() below into a one-argument predicate at_least_80,
#      with partial() or a closure.
#      Use filter() with the predicate on grades and print the resulting list.
#   Print exactly:
#   9
#   9
#   15
#   7
#   [85, 90, 98]
from functools import reduce, partial

nums = [3, 1, 4, 1, 5, 9, 2, 6]
grades = [85, 90, 78, 98]

def meets_minimum(grade, minimum):
    return grade >= minimum

### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
from functools import reduce, partial

# 1. reduce to find max as a fold; in real code, max(nums) is clearer
nums = [3, 1, 4, 1, 5, 9, 2, 6]
maximum = reduce(lambda acc, x: acc if acc > x else x, nums)
print(maximum)    # 9
print(max(nums))  # 9

# 2. partial to create add10
def add(a, b):
    return a + b

add10 = partial(add, 10)
print(add10(5))   # 15
print(add10(-3))  # 7

# 3. Specialize an existing predicate by fixing one keyword argument.
# partial fits because meets_minimum already implements the rule; no extra logic is needed.
# A closure forwarding to meets_minimum(grade, 80) would also be correct.
def meets_minimum(grade, minimum):
    return grade >= minimum

at_least_80 = partial(meets_minimum, minimum=80)
grades = [85, 90, 78, 98]
print(list(filter(at_least_80, grades)))  # [85, 90, 98]
9
9
15
7
[85, 90, 98]

10.2.3.3. functools.lru_cache()#

@lru_cache memoizes a function’s results: the first time a function is called with given arguments, the result is stored. On subsequent calls with the same arguments, the cached result is returned immediately — no recomputation needed.

cache_info() reports hits, the calls answered from the cache, and misses, the calls that ran the function body. LRU stands for Least Recently Used: when the cache is full, the least recently accessed entry is evicted.

The example below decorates the recursive Fibonacci function from 4.3 Recursion. Without the cache, fib(n) solves the same subproblems again and again; with the cache, each fib(k) is computed once and then looked up.

from functools import lru_cache
import time

@lru_cache(maxsize=None)  # unlimited cache
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

# Without the cache, fib(50) would make about 40 billion calls; with it, each fib(k) runs once
start = time.perf_counter()
print(fib(50))   # 12586269025
elapsed = time.perf_counter() - start
print(f'Computed in {elapsed:.6f}s')  # microseconds with cache

# Inspect cache statistics
print(fib.cache_info())  # CacheInfo(hits=..., misses=51, maxsize=None, currsize=51)
12586269025
Computed in 0.000109s
CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)

The same pattern appears in counting problems. Suppose you climb a staircase taking one or two steps at a time, and you want the number of different ways to reach step n. The last move was either a 1-step from n - 1 or a 2-step from n - 2, so ways(n) = ways(n - 1) + ways(n - 2). With 3 stairs there are 3 ways (1+1+1, 1+2, 2+1). This has the same shape as Fibonacci, so the cache helps in the same way. In cache_info(), a miss is a computed call and a hit is a call answered from the cache:

@lru_cache(maxsize=None)
def ways(n):
    if n <= 1:                      # one way to stand still or take a single step
        return 1
    return ways(n - 1) + ways(n - 2)

print(ways(3))              # 3
print(ways(30))             # 1346269
print(ways.cache_info())    # each value of n from 0 to 30 is a miss once: misses=31
3
1346269
CacheInfo(hits=29, misses=31, maxsize=None, currsize=31)

Hits can occur inside a single top-level call. Trace ways(4) with an empty cache. ways(4) needs ways(3) and ways(2). ways(3) needs ways(2) and ways(1), and ways(2) needs ways(1) and ways(0). The first time each of ways(4), ways(3), ways(2), ways(1), and ways(0) is called, it is a miss, which makes 5 misses. Two later requests find a saved answer: the call for ways(1) inside ways(3), and the call for ways(2) inside ways(4). That makes 2 hits. A second top-level call ways(4) is a hit that never runs the body, so the hits become 3 and the misses stay 5.

ways.cache_clear()          # start from an empty cache
ways(4)
print(ways.cache_info())    # hits=2, misses=5
ways(4)
print(ways.cache_info())    # hits=3, misses=5: the repeated call is answered from the cache
CacheInfo(hits=2, misses=5, maxsize=None, currsize=5)
CacheInfo(hits=3, misses=5, maxsize=None, currsize=5)

When is caching safe? A cache skips the function body on a hit. This connects memoization to purity: reusing an answer is safe when the answer depends only on the arguments and skipping the body does not omit needed side effects. The Fibonacci and staircase functions meet these conditions for nonnegative integer inputs.

Check before caching

Why it matters

Are the arguments hashable?

Cache keys use hashing, as dictionary keys do. Integers, strings, and tuples of hashable items work; lists and dictionaries do not.

Does the result depend on changing state outside the arguments?

The cache does not notice changes to a global variable, a file, or a database. A previously saved answer can become stale.

Must the body run on every call?

A cache hit skips logging, random draws, and other effects inside the function.

Does each caller need a fresh mutable result?

The cache returns the saved object itself, so one caller’s mutation can affect another caller.

In the next example, changing settings does not change the argument score. The cache therefore reuses the old answer:

from functools import lru_cache

settings = {'bonus': 5}

@lru_cache(maxsize=2)
def curved_score(score):
    return min(score + settings['bonus'], 100)

print(curved_score(80))       # 85: computes and saves an answer
settings['bonus'] = 10
print(curved_score(80))       # 85: stale answer, because the key is still 80
curved_score.cache_clear()
print(curved_score(80))       # 90: recomputes after clearing the cache
85
85
90

cache_clear() removes all saved entries. It is useful when deliberately invalidating a cache, but remembering to clear it after every external change is fragile. A better design here makes the bonus an explicit argument: curved_score(score, bonus). Then (80, 5) and (80, 10) are different cache keys, and the function no longer reads hidden changing state.

@lru_cache(maxsize=2)
def curved_score_explicit(score, bonus):
    return min(score + bonus, 100)

print(curved_score_explicit(80, 5))    # 85
print(curved_score_explicit(80, 10))   # 90: a different key
85
90

Cache size is a separate decision. @lru_cache(maxsize=2) keeps at most two entries and evicts the least recently used entry when space is needed. @lru_cache() defaults to 128 entries. The recursive examples use maxsize=None: no entries are evicted, so the cache can keep growing. Cached arguments and results remain referenced until eviction or cache_clear(); choose a bound for a long-running program with many distinct inputs.

Practice. Before running the next cell:

  1. Predict both printed lists.

  2. Decide whether labels(3) creates a fresh list on its second call.

  3. Explain why passing [3] as an argument fails before the function body runs.

@lru_cache(maxsize=2)
def labels(score):
    return [f'score={score}']

first = labels(3)
first.append('checked')
print(first)
print(labels(3))

# Intentional error: list arguments cannot be used as cache keys.
try:
    labels([3])
except TypeError as error:
    print(f'TypeError: {error}')
['score=3', 'checked']
['score=3', 'checked']
TypeError: unhashable type: 'list'

Both printed lists are ['score=3', 'checked']. The second call returns the same cached list that first refers to, including the appended item. The final line reports TypeError: unhashable type: 'list': the cache needs a hashable key before it can call labels.

If each caller needs an independent list, leave this function uncached. Another design is to cache immutable data, such as a tuple of strings, and let callers explicitly build their own lists from it. Converting a list argument to a tuple only addresses hashability when its elements are hashable; it does not fix hidden state or shared mutable results.

### Exercise: lru_cache
#   1. Decorate `count_ways(n)` below with @lru_cache(maxsize=None) to speed it up.
#      count_ways(n) returns how many ways to climb n stairs (1 or 2 at a time).
#   2. Clear count_ways's cache, then call count_ways(5) twice. Before running,
#      predict the returned value and cumulative hits/misses after EACH call.
#      Print each value and cache_info().
#   3. Print how many new misses the second call caused, computed from the two cache_info() results.
#   4. A live score lookup takes a student name and reads a dictionary that may
#      change between calls. Choose partial(), lru_cache(), or neither for keeping
#      results current, and print "Live score lookup: " followed by your choice.
#   Print exactly:
#   8
#   CacheInfo(hits=3, misses=6, maxsize=None, currsize=6)
#   8
#   CacheInfo(hits=4, misses=6, maxsize=None, currsize=6)
#   New misses: 0
#   Live score lookup: neither
from functools import lru_cache

def count_ways(n):
    if n <= 1: return 1
    return count_ways(n - 1) + count_ways(n - 2)

### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
from functools import lru_cache

# 1. lru_cache to speed up count_ways
@lru_cache(maxsize=None)
def count_ways(n):
    if n <= 1: return 1
    return count_ways(n - 1) + count_ways(n - 2)

# 2. Start from an empty cache, regardless of previous calls in this notebook.
count_ways.cache_clear()
print(count_ways(5))
first = count_ways.cache_info()
print(first)
# 8; hits=3, misses=6: n=0 through n=5 are computed once each.
# During that computation, n=1, n=2, and n=3 are each reused once.
print(count_ways(5))
second = count_ways.cache_info()
print(second)
# 8; hits=4, misses=6: the top-level call is a hit, so the body never runs.

# 3. No recursive calls are made on the second call, so it adds no misses.
print("New misses:", second.misses - first.misses)

# 4. Neither: read the live dictionary directly for each lookup.
# lru_cache would reuse an old score for the same name after a dictionary update.
# partial only pre-fills arguments; it does not keep cached data up to date.
# Caching would need an explicit invalidation policy or a key reflecting data changes.
print("Live score lookup: neither")
8
CacheInfo(hits=3, misses=6, maxsize=None, currsize=6)
8
CacheInfo(hits=4, misses=6, maxsize=None, currsize=6)
New misses: 0
Live score lookup: neither