{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l16-c000",
   "metadata": {},
   "source": [
    "# Lecture 18 - Repetition 2: Recursion\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Loops are not the only way to make code repeat itself! Somewhat mind-boggingly, perhaps, functions are able to *call themselves*. This is called recursion, which we will explore in this lecture. To understand recursion, however, we will first need to understand recursion.\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- writing recursive functions with base and recursive cases;\n",
    "- following calls and return values through the call stack;\n",
    "- comparing recursive and iterative approaches to repetition;\n",
    "- writing recursive type hints; and\n",
    "- recursively searching and processing data.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Official Python documentation: [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError) and [`sys.getrecursionlimit()`](https://docs.python.org/3/library/sys.html#sys.getrecursionlimit) explain Python's limit on nested calls.\n",
    "- W3Schools: [Recursion](https://www.w3schools.com/python/python_recursion.asp).\n",
    "- Helsinki Python MOOC: [Recursion](https://programming-26.mooc.fi/part-11/3-recursion) for (most of) the content covered in this lecture and [More recursion examples](https://programming-26.mooc.fi/part-11/4-more-recursion-examples) if you'd like a deeper dive into recursive data structures."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a57f13d2",
   "metadata": {},
   "source": [
    "## 1. Recursive functions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c001",
   "metadata": {},
   "source": [
    "Throughout the course, we have automated a lot of tasks using `while` and `for` loops. But these structures are not actually necessary to repeat code, as *functions are able to repeat themselves*.\n",
    "\n",
    "A **recursive function** calls itself as part of its work. There is no difference in syntax between a recursive and non-recursive function - to make a function recursive, you just call it by its name in its own body.\n",
    "\n",
    "Simply having a function call itself with no way to end would lead to an infinite loop, just like a `while True` statement. Therefore, recursive functions tend to be broken up into two parts. First, you need a **base case**, an input that the function can handle without another recursive call. Then, a **recursive case** calls the function on a smaller or simpler part, making progress towards the base case.\n",
    "\n",
    "Take a look at the following function and see if you can make sense of it.\n",
    "\n",
    "**Predict:** What will be printed? Which part of the function is the base case and which the recursive case?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c002",
   "metadata": {},
   "outputs": [],
   "source": [
    "def countdown(number):\n",
    "    if number <= 0:\n",
    "        print(\"Liftoff!\")\n",
    "        return\n",
    "    else:\n",
    "        print(number)\n",
    "        countdown(number - 1)\n",
    "\n",
    "countdown(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c003",
   "metadata": {},
   "source": [
    "In this function, counting down from 3 to 1 are the recursive cases, and when we reach 0 we hit the base case and exit the function.\n",
    "\n",
    "How does this work in practice?\n",
    "\n",
    "When `countdown(3)` reaches `countdown(2)`, the first call pauses. Python keeps track of its local `number` and where it should resume. The new call then has its **own** local `number`!\n",
    "\n",
    "Let's look at a slightly different implementation of this function, where we added a line *after* the recursive call to `countdown`.\n",
    "\n",
    "**Predict:** What order will the `Finished` messages appear in?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d04b508d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def countdown(number):\n",
    "    if number <= 0:\n",
    "        print(\"Liftoff!\")\n",
    "        return\n",
    "    print(number)\n",
    "    countdown(number - 1)\n",
    "    print(\"Finished\", number)\n",
    "\n",
    "countdown(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b011e918",
   "metadata": {},
   "source": [
    "Were you surprised? Let's walk through it one by one.\n",
    "\n",
    "The record for one active call is often called a **stack frame**. The **call stack** keeps these records in order, with the most recent call finishing first:\n",
    "\n",
    "```text\n",
    "countdown(3): prints 3, waits for countdown(2)\n",
    "  countdown(2): prints 2, waits for countdown(1)\n",
    "    countdown(1): prints 1, waits for countdown(0)\n",
    "      countdown(0): prints Lift off!, returns\n",
    "    countdown(1): resumes, prints Finished 1, ends\n",
    "  countdown(2): resumes, prints Finished 2, ends\n",
    "countdown(3): resumes, prints Finished 3, ends\n",
    "```\n",
    "\n",
    "This return journey is called **unwinding** the stack. Notice that the `return` in the base case only ends the *current* call. It doesn't cancel the waiting calls, which still finish one by one.\n",
    "\n",
    "This can be powerful, especially when we make our recursive calls return something.\n",
    "\n",
    "**Predict:** What does `sum_to(4)` return? Start by working out the result for 0, then 1, then 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c004",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_to(number):\n",
    "    if number <= 0:\n",
    "        return 0\n",
    "    return number + sum_to(number - 1)\n",
    "\n",
    "print(sum_to(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db09ddac",
   "metadata": {},
   "source": [
    "In `number + sum_to(number - 1)`, the addition has to wait until the recursive call provides its answer, meaning we add 0, 1, 2, and then 3, in that order:\n",
    "\n",
    "Expanding:\n",
    "- `sum_to(3)` needs `3 + sum_to(2)`\n",
    "- `sum_to(2)` needs `2 + sum_to(1)`\n",
    "- `sum_to(1)` needs `1 + sum_to(0)`\n",
    "\n",
    "And then, returning:\n",
    "- `sum_to(0)` becomes `0` (base case)\n",
    "- `sum_to(1)` becomes `1` (recursive case)\n",
    "- `sum_to(2)` becomes `3` (recursive case)\n",
    "- `sum_to(3)` becomes `6` (recursive case)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c005",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: repeating text</b>\n",
    "\n",
    "Write a recursive function that repeats text. Its base case should return an empty string and its recursive case should add one copy of `text` to the result for one fewer repetition. Test counts of 0, 1, and 3.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c006",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def repeat_text(text, count):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c007",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for the solution</b></summary>\n",
    "\n",
    "```python\n",
    "def repeat_text(text, count):\n",
    "    if count <= 0:\n",
    "        return \"\"\n",
    "    return text + repeat_text(text, count - 1)\n",
    "\n",
    "assert repeat_text(\"ha\", 0) == \"\"\n",
    "assert repeat_text(\"ha\", 1) == \"ha\"\n",
    "assert repeat_text(\"ha\", 3) == \"hahaha\"\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49af2837",
   "metadata": {},
   "source": [
    "## 2. Recursive mathematics"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c008",
   "metadata": {},
   "source": [
    "Let's practice writing some recursive functions by looking at two common maths formulae: calculating factorials and calculating Fibonacci numbers.\n",
    "\n",
    "### Factorials\n",
    "\n",
    "The factorial of a non-negative integer is the product of the positive integers up to it. For example, `4! = 4 × 3 × 2 × 1 = 24`. By definition, `0! = 1`.\n",
    "\n",
    "That gives us a recursive rule: for a positive `n`, `n! = n × (n - 1)!`. As the smaller factorial is the same kind of problem, a recursive function fits this calculation well. Take a look at the implementation below and see if you can trace it. We've used type hints to inform the user that it should only take integers.\n",
    "\n",
    "**Predict:** Before running the function, what should `factorial(1)` return? What would go wrong if the base case returned 0 instead of 1?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c009",
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial(number: int) -> int:\n",
    "    if number < 0:\n",
    "        raise ValueError(\"factorial for negative integers is undefined\")\n",
    "    if number == 0:\n",
    "        return 1\n",
    "    return number * factorial(number - 1)\n",
    "\n",
    "for number in range(6):\n",
    "    print(number, factorial(number))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c010",
   "metadata": {},
   "source": [
    "Returning 0 in the base case would make every later multiplication give 0 too. The base result isn't just there to stop the recursion; it also supplies the value used by the waiting calls.\n",
    "\n",
    "For `factorial(3)`, the calls first ask for `3 * factorial(2)`, then `2 * factorial(1)`, then `1 * factorial(0)`. Once the base case returns 1, the results come back as 1, 2, and 6.\n",
    "\n",
    "To visualise this, we've written a traced version below. It uses a `depth` parameter to indent its messages. The default of 0 is for the first call and each recursive call then adds 1.\n",
    "\n",
    "**Predict:** Which `return` message appears first, and which appears last?\n",
    "\n",
    "**Having trouble following along?** Use the debugger from Tutorial 5 to go through the function step-by-step!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c011",
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial_trace(number: int, depth: int = 0) -> int:\n",
    "    if number < 0:\n",
    "        raise ValueError(\"factorial for negative integers is undefined\")\n",
    "    print(\"  \" * depth + f\"factorial({number})\")\n",
    "    if number == 0:\n",
    "        print(\"  \" * depth + \"return 1\")\n",
    "        return 1\n",
    "    result = number * factorial_trace(number - 1, depth + 1)\n",
    "    print(\"  \" * depth + f\"return {result}\")\n",
    "    return result\n",
    "\n",
    "factorial_trace(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c012",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: recursive powers</b>\n",
    "\n",
    "Write a function that raises a base number to a certain exponent, for example, `2**5 = 32`. A power with exponent 0 is 1; otherwise multiply the base by the result for exponent minus 1. \n",
    "\n",
    "Do not allow negative exponents and test for exponents 0, 1, and a larger value.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c013",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def power(base, exponent):\n",
    "    pass\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c014",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def power(base, exponent):\n",
    "    if exponent < 0:\n",
    "        raise ValueError(\"exponent must be non-negative\")\n",
    "    if exponent == 0:\n",
    "        return 1\n",
    "    return base * power(base, exponent - 1)\n",
    "\n",
    "assert power(5, 0) == 1\n",
    "assert power(5, 1) == 5\n",
    "assert power(2, 5) == 32\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c015",
   "metadata": {},
   "source": [
    "### Fibonacci\n",
    "\n",
    "The Fibonacci sequence begins `0, 1, 1, 2, 3, 5, 8, ...`. Each later number is the sum of the previous two. Using index 0 for the first number, we here have **two base cases**: `fibonacci(0) = 0` and `fibonacci(1) = 1`.\n",
    "\n",
    "Not only do we have two base cases, because we are always adding two numbers together, we are actually also making **two recursive calls** for each larger index. Python evaluates the left call first, gets its result, then evaluates the right call and finally adds the two results together.\n",
    "\n",
    "**Predict:** What does `fibonacci(4)` need to calculate? Where does `fibonacci(2)` occur more than once in those calls?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c016",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fibonacci(index: int) -> int:\n",
    "    if index < 0:\n",
    "        raise ValueError(\"index must be non-negative\")\n",
    "    if index == 0:\n",
    "        return 0\n",
    "    if index == 1:\n",
    "        return 1\n",
    "    return fibonacci(index - 1) + fibonacci(index - 2)\n",
    "\n",
    "print([fibonacci(index) for index in range(16)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c017",
   "metadata": {},
   "source": [
    "Here is the start of the call pattern for index 4:\n",
    "\n",
    "```text\n",
    "fibonacci(4)\n",
    "  fibonacci(3)\n",
    "    fibonacci(2)\n",
    "    fibonacci(1)\n",
    "  fibonacci(2)      <- the same problem again\n",
    "```\n",
    "\n",
    "Each call of `fibonacci(2)` makes more calls of its own. This repetition grows very quickly, so keep the inputs small-ish while experimenting with this version!\n",
    "\n",
    "Of course, recursion is only one way to do repetition. We can also still solve this problem using loops. We would call that an **iterative** solution rather than a recursive one.\n",
    "\n",
    "**Predict:** After one loop iteration, what do `previous` and `current` contain?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c018",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fibonacci_iterative(index: int) -> int:\n",
    "    if index < 0:\n",
    "        raise ValueError(\"index must be non-negative\")\n",
    "    previous = 0\n",
    "    current = 1\n",
    "    for step in range(index):\n",
    "        previous, current = current, previous + current\n",
    "    return previous\n",
    "\n",
    "for index in range(10):\n",
    "    assert fibonacci(index) == fibonacci_iterative(index)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f026607d",
   "metadata": {},
   "source": [
    "This version can just keep the previous two values and calculate each new one once. In the assignment inside the `for` loop, both values on the right are worked out before either value on the left is assigned.\n",
    "\n",
    "Which version of the algorithm is your favourite?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c019",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: count the calls</b>\n",
    "\n",
    "Let's count how many calls a recursive implementation of the Fibonacci algorithm actually takes. Adapt the function above to return a `(value, calls)` tuple instead of just the value. The base call uses one call, and the recursive case takes one call for itself plus every call made by the two smaller problems.\n",
    "\n",
    "Test for indices 0, 1, 5, 10, and 20. Why is it that increasing the index by a little can increase the call count by a lot?\n",
    "\n",
    "Make a separate `counted_fibonacci(index)` return a `(value, calls)` tuple. A base case takes one call. A larger case takes one call for itself, plus every call made by the two smaller problems. Test indices 0, 1, 5, 10, and 20. Explain why increasing the index by a little can increase the call count by a lot.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c020",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def counted_fibonacci(index):\n",
    "\tpass\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c021",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "The call count increases so quickly because each recursive case makes two more calls, increasing exponentially for higher indices.\n",
    "\n",
    "```python\n",
    "def counted_fibonacci(index):\n",
    "    if index < 0:\n",
    "        raise ValueError(\"index must be non-negative\")\n",
    "    if index < 2:\n",
    "        return index, 1\n",
    "    left_value, left_calls = counted_fibonacci(index - 1)\n",
    "    right_value, right_calls = counted_fibonacci(index - 2)\n",
    "    return left_value + right_value, 1 + left_calls + right_calls\n",
    "\n",
    "assert counted_fibonacci(0) == (0, 1)\n",
    "assert counted_fibonacci(1) == (1, 1)\n",
    "for index in [5, 10, 20]:\n",
    "    value, calls = counted_fibonacci(index)\n",
    "    print(index, value, calls)\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "710dedc6",
   "metadata": {},
   "source": [
    "## 3. Recursive type hints"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d2f17ff",
   "metadata": {},
   "source": [
    "Recursion is also allowed as part of type hints!\n",
    "\n",
    "Using the `type` keyword, you may define your own type names, which can then be used recursively.\n",
    "\n",
    "Say that, for example, we have a list that may contain strings, or lists of strings, or lists containing more lists, et cetera. This type can be expressed as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a9b73cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "type NestedStrList = list[str | NestedStrList]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c022",
   "metadata": {},
   "source": [
    "Recursion can be particularly useful when working with this type of data structure, where it has the same shape at several levels.\n",
    "\n",
    "`flatten()` below handles one list at a time. For a string, it appends the item to its result, and for a sublist, it asks a recursive call to flatten that sublist and uses `.extend()` to append all the returned items.\n",
    "\n",
    "Remember `isinstance()`, from Lecure 16, which we can use to check whether something is a list.\n",
    "\n",
    "**Predict:** What flat list will this packing list produce? In what order will the items appear?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c023",
   "metadata": {},
   "outputs": [],
   "source": [
    "type NestedStrList = list[str | NestedStrList]\n",
    "\n",
    "packing_list = [\n",
    "    \"laptop\",\n",
    "    [\"charger\", \"adapter\"],\n",
    "    [\"clothes\", [\"socks\", \"jumper\"]],\n",
    "]\n",
    "\n",
    "def flatten(nested_items: NestedStrList) -> list[str]:\n",
    "    result = []\n",
    "    for item in nested_items:\n",
    "        if isinstance(item, list):\n",
    "            result.extend(flatten(item))\n",
    "        else:\n",
    "            result.append(item)\n",
    "    return result\n",
    "\n",
    "print(flatten(packing_list))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c024",
   "metadata": {},
   "source": [
    "Each call creates its own `result` list. When it encounters a nested list, it waits for the flat result of that smaller part, adds those items, and then continues its own loop.\n",
    "\n",
    "Play around with the contents of `packing_list` to test for edge cases. Does it handle empty lists and simple strings as expected? What about adding even more levels of depth?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c025",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: adding nested numbers</b>\n",
    "\n",
    "Write a function that counts the sum of all numbers in a list that may contain nested lists of numbers.\n",
    "\n",
    "Test `[]`, `[5]`, `[1, [2, [3, 4]], 5]`, as well as a list containing an empty sublist. Add appropriate type hints to document your function.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c026",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def nested_sum(items):\n",
    "    pass\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c027",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "type NestedIntList = list[int | NestedIntList]\n",
    "\n",
    "def nested_sum(items: NestedIntList) -> int:\n",
    "    total = 0\n",
    "    for item in items:\n",
    "        if isinstance(item, list):\n",
    "            total += nested_sum(item)\n",
    "        else:\n",
    "            total += item\n",
    "    return total\n",
    "\n",
    "assert nested_sum([]) == 0\n",
    "assert nested_sum([5]) == 5\n",
    "assert nested_sum([1, [2, [3, 4]], 5]) == 15\n",
    "assert nested_sum([[], 2]) == 2\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "863adaef",
   "metadata": {},
   "source": [
    "## 4. Recursive binary search"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c028",
   "metadata": {},
   "source": [
    "Let's bring it all together with one final algorithm deep dive. In Lecture 17, we discussed binary search, in which each step left a smaller search region. That's a recursive case, as we then search the remaining half using the same rules. Binary search has two base cases: either we find the target, at the middle of our search region, or we find that the region is empty, in which case the target is not present in our list.\n",
    "\n",
    "To write this recursively, we pass `low` and `high` indices directly instead of creating slices. That keeps returned indices relative to the original list and avoids copying part of the list on every call. The default `high=None` means means that we will start on the last index during the initial call.\n",
    "\n",
    "Work through the below algorithm and add comments to it when necessary to explain how it works.\n",
    "\n",
    "**Predict:** Say we are searching for the number 30. After checking the middle item 17, what arguments does the search for 31 pass to its next call? Which base case will end this search?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c029",
   "metadata": {},
   "outputs": [],
   "source": [
    "def recursive_binary_search(items: list[int], target: int, low: int = 0, high: int | None = None) -> int | None:\n",
    "    if high is None:\n",
    "        high = len(items) - 1\n",
    "    if low > high:\n",
    "        return None\n",
    "\n",
    "    middle = (low + high) // 2\n",
    "    if items[middle] == target:\n",
    "        return middle\n",
    "    if items[middle] < target:\n",
    "        return recursive_binary_search(items, target, middle + 1, high)\n",
    "    return recursive_binary_search(items, target, low, middle - 1)\n",
    "\n",
    "values = [3, 8, 12, 17, 25, 31, 44]\n",
    "print(recursive_binary_search(values, 31))\n",
    "print(recursive_binary_search(values, 30))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c030",
   "metadata": {},
   "source": [
    "The precondition of the algorithm is still the same: `items` must be sorted in ascending order using the same comparisons as the search for it to work.\n",
    "\n",
    "### Limits to recursion\n",
    "\n",
    "Every waiting call uses memory for its local state and return position. As we saw with Fibonacci, these calls can increase very quickly, so Python actually has a *limit* to how deeply calls can nest. Going beyond that limit raises a `RecursionError`. This will occur not only when forgetting to provide a base case (causing an infinite loop), but also when you have simply provided too many recursive cases.\n",
    "\n",
    "Python's recursion limit is often 1000 by default, but can be changed in different environments."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c031",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: trace recursive search</b>\n",
    "\n",
    "Write `traced_binary_search()` with a `depth=0` parameter. Print `low`, `high`, and `middle` before each comparison, with indentation showing the depth of the call. Print a different message for an empty region, when you cannot find the item.\n",
    "\n",
    "Test the first, middle, and last values the provided list, one missing value, as well as an empty list.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-c032",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def recursive_binary_search(items: list[int], target: int, low: int = 0, high: int | None = None) -> int | None:\n",
    "    pass\n",
    "\n",
    "values = [3, 8, 12, 17, 25, 31, 44]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-c033",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def traced_binary_search(items: list[int], target: int, low: int = 0, high: int | None = None, depth: int = 0) -> int | None:\n",
    "    if high is None:\n",
    "        high = len(items) - 1\n",
    "    if low > high:\n",
    "        print(\"  \" * depth + f\"empty {low}..{high}\")\n",
    "        return None\n",
    "    middle = (low + high) // 2\n",
    "    print(\"  \" * depth + f\"{low}..{high}, middle {middle}\")\n",
    "    if items[middle] == target:\n",
    "        return middle\n",
    "    if items[middle] < target:\n",
    "        return traced_binary_search(items, target, middle + 1, high, depth + 1)\n",
    "    return traced_binary_search(items, target, low, middle - 1, depth + 1)\n",
    "\n",
    "values = [3, 8, 12, 17, 25, 31, 44]\n",
    "\n",
    "for target in [3, 17, 44, 30]:\n",
    "    print(\"target\", target, \"->\", traced_binary_search(values, target), \"\\n\")\n",
    "print(traced_binary_search([], 3))\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-consolidation-prompt",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "Let's practice recursion one more time... and one more time... and one more time...\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: a nested menu</b>\n",
    "\n",
    "The menu below is saved as a dictionary, with each value as either a price or another menu dictionary. Write `list_items(menu, prefix=\"\")` to return a list of strings such as `Drinks > Tea: £2.40` and `Food > Hot > Soup: £3.50`.\n",
    "\n",
    "For each entry, build the path from the current prefix and the entry's name. If its value is another dictionary, pass that path into a recursive call and extend your result with the returned strings. If it is a price, add a formatted line. Add appropriate type hints to the code.\n",
    "\n",
    "Test the supplied menu, an empty menu, and one with an extra level.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l16-consolidation-work",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "menu = {\n",
    "    \"Drinks\": {\"Tea\": 2.4, \"Coffee\": 2.8},\n",
    "    \"Food\": {\"Hot\": {\"Soup\": 3.5}, \"Cake\": 2.9},\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-consolidation-solution",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "type PriceDict = dict[str, float | PriceDict]\n",
    "\n",
    "menu = {\n",
    "    \"Drinks\": {\"Tea\": 2.4, \"Coffee\": 2.8},\n",
    "    \"Food\": {\"Hot\": {\"Soup\": 3.5}, \"Cake\": 2.9},\n",
    "}\n",
    "\n",
    "def list_items(menu: PriceDict, prefix: str = \"\"):\n",
    "    lines = []\n",
    "    for name, value in menu.items():\n",
    "        if prefix == \"\":\n",
    "            path = name\n",
    "        else:\n",
    "            path = prefix + \" > \" + name\n",
    "        if isinstance(value, dict):\n",
    "            lines.extend(list_items(value, path))\n",
    "        else:\n",
    "            lines.append(f\"{path}: £{value:.2f}\")\n",
    "    return lines\n",
    "\n",
    "assert list_items({}) == []\n",
    "assert list_items({\"Drinks\": {\"Tea\": 2.4}}) == [\"Drinks > Tea: £2.40\"]\n",
    "assert list_items({\"A\": {\"B\": {\"C\": {\"Item\": 1.0}}}}) == [\n",
    "    \"A > B > C > Item: £1.00\"\n",
    "]\n",
    "for line in list_items(menu):\n",
    "    print(line)\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l16-consolidation-summary",
   "metadata": {
    "tags": [
     "summary"
    ]
   },
   "source": [
    "## Summary\n",
    "\n",
    "This lecture was light on new syntax, instead introducing a different way of *thinking* about repetition in code. Thinking recursively might take some time getting used to, but can unlock very powerful ways of approaching problems.\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "\t<dt><b>Recursion</b></dt>\n",
    "\t<dd>Solving a problem using a function that calls itself on a smaller or simpler version of that problem. See also: iteration.</dd>\n",
    "\t<dt><b>Base case</b></dt>\n",
    "\t<dd>The part of a recursive function that is handled without another recursive call, usually ending the function.</dd>\n",
    "\t<dt><b>Recursive case</b></dt>\n",
    "\t<dd>The part of a recursive function calls itself and, where needed, combines its result with other work.</dd>\n",
    "\t<dt><b>Call stack</b></dt>\n",
    "\t<dd>The record of active function calls and where they will resume when later calls return.</dd>\n",
    "\t<dt><b>Stack frame</b></dt>\n",
    "\t<dd>The local state and return information belonging to one active function call.</dd>\n",
    "\t<dt><b>Unwinding</b></dt>\n",
    "\t<dd>Returning through waiting function calls, with the most recent call finishing first.</dd>\n",
    "\t<dt><b>Iteration</b></dt>\n",
    "\t<dd>Repeating work using a loop. See also: recursion.</dd>\n",
    "\t<dt><b>Recursion depth</b></dt>\n",
    "\t<dd>The number of recursive calls active at once. Python has an (adjustable) limit to this.</dd>\n",
    "</dl>\n",
    "\n",
    "### New syntax\n",
    "\n",
    "<dl>\n",
    "\t<dt><code>type NestedList = list[item | NestedList]</code></dt>\n",
    "\t<dd>Defines a type for a list that may contain values of type <code>item</code>, lists of those values, or lists of those lists, recursively.</dd>\n",
    "\t<dt><code>RecursionError</code></dt>\n",
    "\t<dd>The exception raised when Python's limit on nested calls is exceeded.</dd>\n",
    "</dl>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
