{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "# Functional Practice\n"
   ],
   "id": "VSC-fea3876d"
  },
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "This section applies the ideas from {doc}`Functional Programming <1001-func-prog>` 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.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2198d211",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f314860-9191-42fe-ada7-b63b49e61179",
   "metadata": {},
   "source": [
    "## Recursion\n",
    "\n",
    "Recursion is taught in {doc}`4.3 Recursion <../04-functions/0403-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.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-5f314860-9191-42fe-a",
   "metadata": {},
   "source": [
    "```{index} recursion, base case, recursive case\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-tree-md",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3e0a1fa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "project\n",
      "  README.md\n",
      "  data\n",
      "    sales.csv\n",
      "  src\n",
      "    main.py\n",
      "    utils\n",
      "      helpers.py\n"
     ]
    }
   ],
   "source": [
    "# Tree traversal: the same function handles every level of the folder tree\n",
    "import os\n",
    "import tempfile\n",
    "\n",
    "def print_directory(path, level=0):\n",
    "    \"\"\"Print a folder and everything inside it, indented by depth.\"\"\"\n",
    "    print('  ' * level + os.path.basename(path))\n",
    "    if os.path.isdir(path):                         # a file is the base case: nothing more to visit\n",
    "        for item in sorted(os.listdir(path)):       # recursive case: visit each child one level deeper\n",
    "            print_directory(os.path.join(path, item), level + 1)\n",
    "\n",
    "# Build a small sample tree in a temporary folder\n",
    "with tempfile.TemporaryDirectory() as root:\n",
    "    project = os.path.join(root, 'project')\n",
    "    for folder in ['data', 'src/utils']:\n",
    "        os.makedirs(os.path.join(project, folder))\n",
    "    for name in ['README.md', 'data/sales.csv', 'src/main.py', 'src/utils/helpers.py']:\n",
    "        open(os.path.join(project, name), 'w').close()\n",
    "\n",
    "    print_directory(project)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-value-md",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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:\n",
    "\n",
    "```text\n",
    "factorial(4)\n",
    "= 4 * factorial(3)\n",
    "= 4 * (3 * factorial(2))\n",
    "= 4 * (3 * (2 * factorial(1)))\n",
    "= 4 * (3 * (2 * (1 * factorial(0))))\n",
    "= 4 * (3 * (2 * (1 * 1)))      # base case reached: factorial(0) returns 1\n",
    "= 24\n",
    "```\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-value-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial(n):\n",
    "    if n == 0:                      # base case: stop here\n",
    "        return 1\n",
    "    return n * factorial(n - 1)     # recursive case: multiply by the smaller answer\n",
    "\n",
    "def count_digits(n):\n",
    "    if n < 10:                      # base case: a single digit\n",
    "        return 1\n",
    "    return 1 + count_digits(n // 10)    # drop the last digit, count it as 1\n",
    "\n",
    "print(factorial(4))         # 24\n",
    "print(count_digits(1234))   # 4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43762687",
   "metadata": {},
   "source": [
    "### Recursion vs Iteration\n",
    "\n",
    "**Advantages of recursion:**\n",
    "- Elegant and intuitive for certain problems\n",
    "- Mirrors mathematical definitions\n",
    "- Good for tree/graph traversal\n",
    "\n",
    "**Disadvantages:**\n",
    "- Can be slower due to function call overhead\n",
    "- Risk of stack overflow with deep recursion\n",
    "- May use more memory\n",
    "\n",
    "**Python recursion limit:** Python has a default recursion limit (usually 1000). You can check it with `sys.getrecursionlimit()`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-43762687",
   "metadata": {},
   "source": [
    "```{index} recursion limit, sys.getrecursionlimit()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-iter-md",
   "metadata": {},
   "source": [
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-iter-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial_recursive(n):\n",
    "    if n == 0:\n",
    "        return 1\n",
    "    return n * factorial_recursive(n - 1)\n",
    "\n",
    "def factorial_iterative(n):\n",
    "    result = 1\n",
    "    for k in range(2, n + 1):       # mutates result and k: the imperative style\n",
    "        result *= k\n",
    "    return result\n",
    "\n",
    "print(factorial_recursive(10), factorial_iterative(10))     # 3628800 3628800"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-limit-md",
   "metadata": {},
   "source": [
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-limit-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "print(sys.getrecursionlimit())      # 1000 by default\n",
    "\n",
    "try:\n",
    "    factorial_recursive(5000)       # needs 5000 nested calls\n",
    "except RecursionError as error:\n",
    "    print(\"RecursionError:\", error)\n",
    "\n",
    "print(factorial_iterative(5000).bit_length())       # the loop handles it: 5000! needs 54233 bits"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-choose-md",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nested-lead",
   "metadata": {},
   "source": [
    "### Recursion on Nested Data\n",
    "\n",
    "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:\n",
    "\n",
    "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.\n",
    "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()`.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "nested-depth",
   "metadata": {},
   "outputs": [],
   "source": [
    "def depth(data):\n",
    "    if not isinstance(data, list):      # base case: a number has no list inside\n",
    "        return 0\n",
    "    deepest = 0\n",
    "    for item in data:                   # recursive case: ask about each element\n",
    "        deepest = max(deepest, depth(item))\n",
    "    return 1 + deepest                  # this list adds one level to its deepest element\n",
    "\n",
    "print(depth(5))                 # 0\n",
    "print(depth([]))                # 1: an empty list is one level with nothing inside\n",
    "print(depth([1, 2]))            # 1\n",
    "print(depth([1, [2, [3]]]))     # 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nested-trace",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-practice",
   "metadata": {},
   "source": [
    "### Practice\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-practice-countdown",
   "metadata": {},
   "source": [
    "#### Count Down\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3c7aec0",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Count Down\n",
    "#   Write `count_down(n)` that prints n, n-1, ..., 1, then \"Blastoff!\".\n",
    "#   Base case: n <= 0 -> print \"Blastoff!\" and return.\n",
    "#   Recursive case: print n, then call count_down(n - 1).\n",
    "#   Call count_down(3). Expected output: 3, 2, 1, Blastoff! on separate lines.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d35e833f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "def count_down(n):\n",
    "    if n <= 0:\n",
    "        print(\"Blastoff!\")\n",
    "    else:\n",
    "        print(n)\n",
    "        count_down(n - 1)\n",
    "\n",
    "count_down(3)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-practice-sumdigits",
   "metadata": {},
   "source": [
    "#### Sum Digits\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-sumdigits-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Sum Digits\n",
    "#   Write `sum_digits(n)` that returns the sum of the digits of a positive integer.\n",
    "#   Base case: n < 10 -> return n.\n",
    "#   Recursive case: add the last digit (n % 10) to sum_digits of the rest of the number (n // 10).\n",
    "#   Print sum_digits(1234) and sum_digits(99). Expected output: 10 and then 18.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-sumdigits-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "def sum_digits(n):\n",
    "    if n < 10:\n",
    "        return n\n",
    "    return n % 10 + sum_digits(n // 10)\n",
    "\n",
    "print(sum_digits(1234))  # 10\n",
    "print(sum_digits(99))    # 18\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-rec-practice-nested",
   "metadata": {},
   "source": [
    "#### Nested Data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-nested-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Nested Data\n",
    "#   A nested list holds numbers and other lists, like a folder holds files and folders.\n",
    "#   Unlike the first two tasks, this data has no fixed depth, so a fixed set of nested loops cannot reach every level.\n",
    "#   1. Write `total_items(data)` that returns how many numbers the nested list holds.\n",
    "#      Base case: an item that is not a list counts as 1 (test it with isinstance(item, list)).\n",
    "#      Recursive case: for a list, add up total_items() of each element in it.\n",
    "#   2. Print total_items(basket).\n",
    "#   3. Count the items with a single loop over `basket` alone (no recursion), and print that count\n",
    "#      to see what the loop misses.\n",
    "#   Print exactly:\n",
    "#   7\n",
    "#   3\n",
    "basket = [3, [5, 8], [[2], 4, [1, 6]]]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-rec-nested-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "basket = [3, [5, 8], [[2], 4, [1, 6]]]\n",
    "\n",
    "def total_items(data):\n",
    "    if not isinstance(data, list):      # base case: a single number\n",
    "        return 1\n",
    "    total = 0\n",
    "    for item in data:                   # recursive case: add up each element\n",
    "        total += total_items(item)\n",
    "    return total\n",
    "\n",
    "print(total_items(basket))              # 7\n",
    "\n",
    "count = 0\n",
    "for item in basket:\n",
    "    count += 1\n",
    "print(count)                            # 3\n",
    "# A loop over basket alone counts [5, 8] and [[2], 4, [1, 6]] as one item each,\n",
    "# because it does not look inside the nested lists."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "recloop-head",
   "metadata": {},
   "source": [
    "#### Recursion or Loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "recloop-ex",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Recursion or Loop\n",
    "#   Write `sum_to` two ways. Each version returns 1 + 2 + ... + n for n >= 0.\n",
    "#   1. `sum_to_recursive(n)`: base case n == 0 returns 0; otherwise n + sum_to_recursive(n - 1).\n",
    "#   2. `sum_to_iterative(n)`: a for loop over range(1, n + 1) with a running total.\n",
    "#   3. Print both results for n = 10, on one line.\n",
    "#   4. Call sum_to_recursive(5000) inside try/except RecursionError and print \"RecursionError\"\n",
    "#      when it fails. Then print sum_to_iterative(5000).\n",
    "#   5. Decide which version suits a sequence of 100000 values, and print\n",
    "#      \"Use for 100000 values: \" followed by \"recursive\" or \"iterative\".\n",
    "#   Print exactly:\n",
    "#   55 55\n",
    "#   RecursionError\n",
    "#   12502500\n",
    "#   Use for 100000 values: iterative\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "recloop-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "55 55\n",
      "RecursionError\n",
      "12502500\n",
      "Use for 100000 values: iterative\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def sum_to_recursive(n):\n",
    "    if n == 0:\n",
    "        return 0\n",
    "    return n + sum_to_recursive(n - 1)\n",
    "\n",
    "def sum_to_iterative(n):\n",
    "    total = 0\n",
    "    for k in range(1, n + 1):\n",
    "        total += k\n",
    "    return total\n",
    "\n",
    "print(sum_to_recursive(10), sum_to_iterative(10))       # 55 55\n",
    "try:\n",
    "    print(sum_to_recursive(5000))\n",
    "except RecursionError:\n",
    "    print(\"RecursionError\")                             # 5000 nested calls exceed the default limit\n",
    "print(sum_to_iterative(5000))                           # 12502500\n",
    "# Use the loop for 100000 values: the sequence is flat, so recursion adds a stack frame\n",
    "# per value for no benefit and would exceed the recursion limit.\n",
    "print(\"Use for 100000 values: iterative\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d89b6fe6",
   "metadata": {},
   "source": [
    "## Context Managers\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cm-before-text",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "cm-before-code",
   "metadata": {},
   "source": [
    "# By hand: you must remember the cleanup on every path\n",
    "print(\"Open report\")\n",
    "try:\n",
    "    print(\"Writing report\")\n",
    "finally:\n",
    "    print(\"Close report\")         # runs even if the block above raises"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "cm-before-after",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d89b6fe6",
   "metadata": {},
   "source": [
    "```{index} context manager, with statement, contextmanager decorator (@contextmanager)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cm-yield-md",
   "metadata": {},
   "source": [
    "The `@contextmanager` decorator from `contextlib` turns a function that contains `yield` into a context manager. The function runs in three parts:\n",
    "\n",
    "- **Setup.** When the `with` statement starts, the code before `yield` runs.\n",
    "- **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.\n",
    "- **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.\n",
    "\n",
    "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.\n",
    "\n",
    "A function that pauses at `yield` is called a generator function. This section uses `yield` only inside `@contextmanager`; {doc}`11.2 Generators <../11-iter-gen/1102-generators>` covers `yield` and generator functions fully."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4689ec98",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Timer started\n",
      "Work started at: 608446.174127916\n",
      "Timer finished: 0.1051 seconds\n"
     ]
    }
   ],
   "source": [
    "# Creating context managers using contextlib\n",
    "from contextlib import contextmanager\n",
    "import time\n",
    "\n",
    "@contextmanager\n",
    "def timer():\n",
    "    start_time = time.perf_counter()\n",
    "    print(\"Timer started\")\n",
    "    try:\n",
    "        yield start_time\n",
    "    finally:\n",
    "        end_time = time.perf_counter()\n",
    "        print(f\"Timer finished: {end_time - start_time:.4f} seconds\")\n",
    "\n",
    "# Using the timer context manager\n",
    "with timer() as start:\n",
    "    time.sleep(0.1)  # Simulate some work\n",
    "    print(f\"Work started at: {start}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cm-raise-md",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ch10-cm-raise-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Open sales\n",
      "Reading SALES\n",
      "Close sales\n",
      "Open orders\n",
      "Reading ORDERS\n",
      "Close orders\n",
      "Caught: bad record\n"
     ]
    }
   ],
   "source": [
    "from contextlib import contextmanager\n",
    "\n",
    "@contextmanager\n",
    "def opened(name):\n",
    "    print(f\"Open {name}\")         # setup: runs when the with block starts\n",
    "    try:\n",
    "        yield name.upper()        # pause: this value is bound by `as`\n",
    "    finally:\n",
    "        print(f\"Close {name}\")    # cleanup: runs even if the block raises\n",
    "\n",
    "# A block that finishes normally\n",
    "with opened(\"sales\") as label:\n",
    "    print(f\"Reading {label}\")\n",
    "\n",
    "# A block that raises: cleanup runs, then the error reaches the outer except\n",
    "try:\n",
    "    with opened(\"orders\") as label:\n",
    "        print(f\"Reading {label}\")\n",
    "        raise ValueError(\"bad record\")\n",
    "except ValueError as error:\n",
    "    print(f\"Caught: {error}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cm-nest-md",
   "metadata": {},
   "source": [
    "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?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-cm-nest-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from contextlib import contextmanager\n",
    "\n",
    "@contextmanager\n",
    "def tag(name):\n",
    "    print(f\"<{name}>\")\n",
    "    try:\n",
    "        yield\n",
    "    finally:\n",
    "        print(f\"</{name}>\")\n",
    "\n",
    "with tag(\"outer\"):\n",
    "    with tag(\"inner\"):\n",
    "        print(\"text\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cm-nest-answer",
   "metadata": {},
   "source": [
    "The output is `<outer>`, `<inner>`, `text`, `</inner>`, `</outer>`. The `inner` block is entered last, so it is cleaned up first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-cm-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Context Managers\n",
    "#   1. Write a context manager `section(title)` with @contextmanager.\n",
    "#      On entry it prints \"=== title ===\". On exit it prints \"=== end title ===\".\n",
    "#      Use try/finally so the closing line always prints.\n",
    "#   2. Use `section(\"Load\")` in a with block that prints \"Reading data\" and then\n",
    "#      raises KeyError(\"missing\"). Wrap the with statement in try/except KeyError and\n",
    "#      print \"Caught: ...\" in the except clause.\n",
    "#      Check the order of the printed lines: the closing line must come before \"Caught\".\n",
    "from contextlib import contextmanager\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-cm-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "from contextlib import contextmanager\n",
    "\n",
    "@contextmanager\n",
    "def section(title):\n",
    "    print(f\"=== {title} ===\")\n",
    "    try:\n",
    "        yield\n",
    "    finally:\n",
    "        print(f\"=== end {title} ===\")\n",
    "\n",
    "try:\n",
    "    with section(\"Load\"):\n",
    "        print(\"Reading data\")\n",
    "        raise KeyError(\"missing\")\n",
    "except KeyError as error:\n",
    "    print(f\"Caught: {error}\")\n",
    "# === Load ===\n",
    "# Reading data\n",
    "# === end Load ===\n",
    "# Caught: 'missing'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa05ba0e",
   "metadata": {},
   "source": [
    "## The `functools` Module\n",
    "\n",
    "The `functools` module provides higher-order functions that operate on or\n",
    "return other functions. Three particularly useful tools are `reduce`,\n",
    "`partial`, and `lru_cache`. Each answers a different question: how do I combine many\n",
    "values into one (`reduce`), how do I fix some arguments of a function in advance\n",
    "(`partial`), and how do I avoid repeating an expensive call (`lru_cache`)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-fa05ba0e",
   "metadata": {},
   "source": [
    "```{index} functools module\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54599d7a",
   "metadata": {},
   "source": [
    "### `functools.reduce()`\n",
    "\n",
    "You met `reduce()` and its initializer in {doc}`Functional Programming <1001-func-prog>`. Think of it as a **fold**: it combines the items left to right into one accumulated value.\n",
    "\n",
    "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.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-54599d7a",
   "metadata": {},
   "source": [
    "```{index} reduce(), fold\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55e3bdb5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n",
      "[1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "from functools import reduce\n",
    "\n",
    "# Flatten a list of lists: the accumulator is a list, so + concatenates\n",
    "nested = [[1, 2], [3, 4], [5, 6]]\n",
    "flat = reduce(lambda acc, x: acc + x, nested, [])\n",
    "print(flat)     # [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "# In practice, prefer a nested comprehension for flattening; it reads more clearly.\n",
    "print([item for group in nested for item in group])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e9c7b1d",
   "metadata": {},
   "source": [
    "### `functools.partial()`\n",
    "\n",
    "`partial(function, *args, **kwargs)` returns a new function with some\n",
    "arguments pre-filled. This is called **partial application** — useful for\n",
    "creating specialized versions of general-purpose functions.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-8e9c7b1d",
   "metadata": {},
   "source": [
    "```{index} partial(), partial application\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e111e046",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16\n",
      "27\n",
      "Name | Score | Grade\n"
     ]
    }
   ],
   "source": [
    "from functools import partial\n",
    "\n",
    "def power(base, exponent):\n",
    "    return base ** exponent\n",
    "\n",
    "square = partial(power, exponent=2)     # exponent is fixed by keyword\n",
    "cube   = partial(power, exponent=3)\n",
    "\n",
    "print(square(4))   # 16\n",
    "print(cube(3))     # 27\n",
    "\n",
    "# Practical: pre-configure print with a separator\n",
    "header = partial(print, sep=' | ')\n",
    "header('Name', 'Score', 'Grade')  # Name | Score | Grade"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-partial-pos-md",
   "metadata": {},
   "source": [
    "`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)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-partial-pos-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "add10 = partial(add, 10)        # 10 fills a, the first parameter\n",
    "print(add10(5))                 # 15\n",
    "\n",
    "# Common mistake: a positional value fills the FIRST parameter\n",
    "power_of_2 = partial(power, 2)  # base=2, not exponent=2\n",
    "print(power_of_2(5))            # 32, which is 2 ** 5; square(5) would give 25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-reduce-partial-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: reduce and partial\n",
    "#   1. Use reduce() to build the maximum of nums as a fold, to see how folding works,\n",
    "#      and print it. (Hint: lambda acc, x: acc if acc > x else x)\n",
    "#      Then print the same maximum with the built-in you would use for this in real code.\n",
    "#   2. Use partial() to create `add10`, a function that adds 10 to any number.\n",
    "#      Print add10(5) and add10(-3).\n",
    "#   3. Specialize meets_minimum() below into a one-argument predicate at_least_80,\n",
    "#      with partial() or a closure.\n",
    "#      Use filter() with the predicate on grades and print the resulting list.\n",
    "#   Print exactly:\n",
    "#   9\n",
    "#   9\n",
    "#   15\n",
    "#   7\n",
    "#   [85, 90, 98]\n",
    "from functools import reduce, partial\n",
    "\n",
    "nums = [3, 1, 4, 1, 5, 9, 2, 6]\n",
    "grades = [85, 90, 78, 98]\n",
    "\n",
    "def meets_minimum(grade, minimum):\n",
    "    return grade >= minimum\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-reduce-partial-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n",
      "9\n",
      "15\n",
      "7\n",
      "[85, 90, 98]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from functools import reduce, partial\n",
    "\n",
    "# 1. reduce to find max as a fold; in real code, max(nums) is clearer\n",
    "nums = [3, 1, 4, 1, 5, 9, 2, 6]\n",
    "maximum = reduce(lambda acc, x: acc if acc > x else x, nums)\n",
    "print(maximum)    # 9\n",
    "print(max(nums))  # 9\n",
    "\n",
    "# 2. partial to create add10\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "add10 = partial(add, 10)\n",
    "print(add10(5))   # 15\n",
    "print(add10(-3))  # 7\n",
    "\n",
    "# 3. Specialize an existing predicate by fixing one keyword argument.\n",
    "# partial fits because meets_minimum already implements the rule; no extra logic is needed.\n",
    "# A closure forwarding to meets_minimum(grade, 80) would also be correct.\n",
    "def meets_minimum(grade, minimum):\n",
    "    return grade >= minimum\n",
    "\n",
    "at_least_80 = partial(meets_minimum, minimum=80)\n",
    "grades = [85, 90, 78, 98]\n",
    "print(list(filter(at_least_80, grades)))  # [85, 90, 98]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef85ae31",
   "metadata": {},
   "source": [
    "### `functools.lru_cache()`\n",
    "\n",
    "`@lru_cache` memoizes a function's results: the first time a function is\n",
    "called with given arguments, the result is stored. On subsequent calls with\n",
    "the same arguments, the cached result is returned immediately — no\n",
    "recomputation needed.\n",
    "\n",
    "`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\n",
    "recently accessed entry is evicted.\n",
    "\n",
    "The example below decorates the recursive Fibonacci function from {doc}`4.3 Recursion <../04-functions/0403-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.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ef85ae31",
   "metadata": {},
   "source": [
    "```{index} lru_cache(), memoization, LRU cache\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c30eb06",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12586269025\n",
      "Computed in 0.000056s\n",
      "CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)\n"
     ]
    }
   ],
   "source": [
    "from functools import lru_cache\n",
    "import time\n",
    "\n",
    "@lru_cache(maxsize=None)  # unlimited cache\n",
    "def fib(n):\n",
    "    if n <= 1:\n",
    "        return n\n",
    "    return fib(n - 1) + fib(n - 2)\n",
    "\n",
    "# Without the cache, fib(50) would make about 40 billion calls; with it, each fib(k) runs once\n",
    "start = time.perf_counter()\n",
    "print(fib(50))   # 12586269025\n",
    "elapsed = time.perf_counter() - start\n",
    "print(f'Computed in {elapsed:.6f}s')  # microseconds with cache\n",
    "\n",
    "# Inspect cache statistics\n",
    "print(fib.cache_info())  # CacheInfo(hits=..., misses=51, maxsize=None, currsize=51)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-stairs-md",
   "metadata": {},
   "source": [
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-stairs-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "@lru_cache(maxsize=None)\n",
    "def ways(n):\n",
    "    if n <= 1:                      # one way to stand still or take a single step\n",
    "        return 1\n",
    "    return ways(n - 1) + ways(n - 2)\n",
    "\n",
    "print(ways(3))              # 3\n",
    "print(ways(30))             # 1346269\n",
    "print(ways.cache_info())    # each value of n from 0 to 30 is a miss once: misses=31"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ways-trace",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ways-trace-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "ways.cache_clear()          # start from an empty cache\n",
    "ways(4)\n",
    "print(ways.cache_info())    # hits=2, misses=5\n",
    "ways(4)\n",
    "print(ways.cache_info())    # hits=3, misses=5: the repeated call is answered from the cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cache-safety-md",
   "metadata": {},
   "source": [
    "**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.\n",
    "\n",
    "| Check before caching | Why it matters |\n",
    "|---|---|\n",
    "| 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. |\n",
    "| 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. |\n",
    "| Must the body run on every call? | A cache hit skips logging, random draws, and other effects inside the function. |\n",
    "| Does each caller need a fresh mutable result? | The cache returns the saved object itself, so one caller's mutation can affect another caller. |\n",
    "\n",
    "In the next example, changing `settings` does not change the argument `score`. The cache therefore reuses the old answer:\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-cache-stale-code",
   "metadata": {},
   "source": [
    "from functools import lru_cache\n",
    "\n",
    "settings = {'bonus': 5}\n",
    "\n",
    "@lru_cache(maxsize=2)\n",
    "def curved_score(score):\n",
    "    return min(score + settings['bonus'], 100)\n",
    "\n",
    "print(curved_score(80))       # 85: computes and saves an answer\n",
    "settings['bonus'] = 10\n",
    "print(curved_score(80))       # 85: stale answer, because the key is still 80\n",
    "curved_score.cache_clear()\n",
    "print(curved_score(80))       # 90: recomputes after clearing the cache\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "85\n",
      "85\n",
      "90\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cache-repair-md",
   "metadata": {},
   "source": [
    "`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.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-cache-explicit-code",
   "metadata": {},
   "source": [
    "@lru_cache(maxsize=2)\n",
    "def curved_score_explicit(score, bonus):\n",
    "    return min(score + bonus, 100)\n",
    "\n",
    "print(curved_score_explicit(80, 5))    # 85\n",
    "print(curved_score_explicit(80, 10))   # 90: a different key\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "85\n",
      "90\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cache-size-md",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "**Practice.** Before running the next cell:\n",
    "\n",
    "1. Predict both printed lists.\n",
    "2. Decide whether `labels(3)` creates a fresh list on its second call.\n",
    "3. Explain why passing `[3]` as an argument fails before the function body runs.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-cache-sharing-code",
   "metadata": {},
   "source": [
    "@lru_cache(maxsize=2)\n",
    "def labels(score):\n",
    "    return [f'score={score}']\n",
    "\n",
    "first = labels(3)\n",
    "first.append('checked')\n",
    "print(first)\n",
    "print(labels(3))\n",
    "\n",
    "# Intentional error: list arguments cannot be used as cache keys.\n",
    "try:\n",
    "    labels([3])\n",
    "except TypeError as error:\n",
    "    print(f'TypeError: {error}')\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['score=3', 'checked']\n",
      "['score=3', 'checked']\n",
      "TypeError: unhashable type: 'list'\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-cache-feedback-md",
   "metadata": {},
   "source": [
    "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`.\n",
    "\n",
    "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.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9447548f",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: lru_cache\n",
    "#   1. Decorate `count_ways(n)` below with @lru_cache(maxsize=None) to speed it up.\n",
    "#      count_ways(n) returns how many ways to climb n stairs (1 or 2 at a time).\n",
    "#   2. Clear count_ways's cache, then call count_ways(5) twice. Before running,\n",
    "#      predict the returned value and cumulative hits/misses after EACH call.\n",
    "#      Print each value and cache_info().\n",
    "#   3. Print how many new misses the second call caused, computed from the two cache_info() results.\n",
    "#   4. A live score lookup takes a student name and reads a dictionary that may\n",
    "#      change between calls. Choose partial(), lru_cache(), or neither for keeping\n",
    "#      results current, and print \"Live score lookup: \" followed by your choice.\n",
    "#   Print exactly:\n",
    "#   8\n",
    "#   CacheInfo(hits=3, misses=6, maxsize=None, currsize=6)\n",
    "#   8\n",
    "#   CacheInfo(hits=4, misses=6, maxsize=None, currsize=6)\n",
    "#   New misses: 0\n",
    "#   Live score lookup: neither\n",
    "from functools import lru_cache\n",
    "\n",
    "def count_ways(n):\n",
    "    if n <= 1: return 1\n",
    "    return count_ways(n - 1) + count_ways(n - 2)\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf91dd14",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n",
      "CacheInfo(hits=3, misses=6, maxsize=None, currsize=6)\n",
      "8\n",
      "CacheInfo(hits=4, misses=6, maxsize=None, currsize=6)\n",
      "New misses: 0\n",
      "Live score lookup: neither\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from functools import lru_cache\n",
    "\n",
    "# 1. lru_cache to speed up count_ways\n",
    "@lru_cache(maxsize=None)\n",
    "def count_ways(n):\n",
    "    if n <= 1: return 1\n",
    "    return count_ways(n - 1) + count_ways(n - 2)\n",
    "\n",
    "# 2. Start from an empty cache, regardless of previous calls in this notebook.\n",
    "count_ways.cache_clear()\n",
    "print(count_ways(5))\n",
    "first = count_ways.cache_info()\n",
    "print(first)\n",
    "# 8; hits=3, misses=6: n=0 through n=5 are computed once each.\n",
    "# During that computation, n=1, n=2, and n=3 are each reused once.\n",
    "print(count_ways(5))\n",
    "second = count_ways.cache_info()\n",
    "print(second)\n",
    "# 8; hits=4, misses=6: the top-level call is a hit, so the body never runs.\n",
    "\n",
    "# 3. No recursive calls are made on the second call, so it adds no misses.\n",
    "print(\"New misses:\", second.misses - first.misses)\n",
    "\n",
    "# 4. Neither: read the live dictionary directly for each lookup.\n",
    "# lru_cache would reuse an old score for the same name after a dictionary update.\n",
    "# partial only pre-fills arguments; it does not keep cached data up to date.\n",
    "# Caching would need an explicit invalidation policy or a key reflecting data changes.\n",
    "print(\"Live score lookup: neither\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
