{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ed7c7e8b-9381-4a10-a211-fa0853b53e54",
   "metadata": {},
   "source": [
    "# Functional Concepts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c9f1a523",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "1d92f137",
   "metadata": {},
   "source": [
    "In Chapter 9, you organized programs around objects that combine related data and behavior. **Encapsulation** makes changes to an object's state explicit and controlled. **Functional programming** approaches the same design goal from another direction: express calculations as transformations from inputs to outputs, with fewer hidden changes to shared data. Both approaches help you organize a program so that changes are easier to understand and control.\n",
    "\n",
    "This section builds the functional side of that partnership: purity controls effects, functions as values enable composition, and higher-order functions, closures, decorators, and comprehensions provide tools for combining behavior. Python supports these tools alongside classes, so you can use both approaches in one program. A table later in this section follows the gradebook example through four design concerns.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc36e197",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "148683c7",
   "metadata": {},
   "source": [
    "## FP in Python\n",
    "\n",
    "**Functional programming (FP)** is a programming paradigm that treats computation as the evaluation of mathematical functions. Imperative programs describe *how* to do something step by step, often by changing program state. Functional programs instead describe *what* to compute by transforming inputs into outputs.\n",
    "\n",
    "```text\n",
    "                         ┌──────────────────────┐\n",
    "                         │ Programming Paradigm │\n",
    "                         └──────────┬───────────┘\n",
    "                  ┌─────────────────┴─────────────────┐     \n",
    "                  ▼                                   ▼\n",
    "          ┌───────────────┐                   ┌───────────────┐\n",
    "          │  Imperative   │                   │  Declarative  │\n",
    "          └───────┬───────┘                   └───────┬───────┘\n",
    "          ┌───────┴───────┐                   ┌───────┴───────┐\n",
    "          ▼               ▼                   ▼               ▼\n",
    "┌────────────────┐ ┌────────────────┐ ┌────────────┐     ┌─────────┐\n",
    "│  Procedural    │ │ Object-Oriented│ │ Functional │     │ Logic   │\n",
    "└───────┬────────┘ └───────┬────────┘ └─────┬──────┘     └────┬────┘\n",
    "        ▼                  ▼                ▼                 ▼\n",
    "  C, Basic, Fortran     C++, Java      Haskell, Elm       Prolog, Datalog\n",
    "        \n",
    "```\n",
    "Source: Kumar, \"Programming Paradigms\" {cite}`kumar_paradigms`.[^paradigms]\n",
    "\n",
    "Popular Functional Programming Languages:\n",
    "- Pure: Haskell, Elm\n",
    "- Hybrid/Multi-paradigm: Scala (dual-first), Kotlin (OO-first), F# (function-first), Elixir, Clojure.\n",
    "- FP-enabled: JavaScript, **Python**, Rust, Swift\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-148683c7",
   "metadata": {},
   "source": [
    "```{index} functional programming, programming paradigm\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "014a0078",
   "metadata": {},
   "source": [
    "Key principles of functional programming:\n",
    "\n",
    "- **Pure functions**: a function always returns the same output for the same input and has no side effects (it doesn't modify external state, perform I/O, or use randomness). For example, `math.sqrt(4)` is pure; `random.random()` is not.\n",
    "- **Immutability**: data is not modified in place; new values are produced instead. For example, instead of modifying a list, you produce a new one. This removes a class of bugs caused by unexpected changes to shared data. The benefits below explain what this does and does not guarantee for concurrent code.\n",
    "- **First-class functions**: functions are treated like any other value: they can be assigned to variables, passed as arguments, and returned from other functions.\n",
    "- **Higher-order functions**: functions that work with other functions by accepting them as arguments or returning them (e.g., `map()`, `filter()`, `sorted()`); the Higher-Order Functions section defines the term in full.\n",
    "\n",
    "These principles answer different questions. First-class functions and higher-order functions describe how functions can be stored, passed, or returned. Purity describes what happens when a function runs. Passing a function to `map()`, writing a lambda, or applying a decorator does not by itself make the resulting computation pure: the functions being called may read changing state or perform side effects.\n",
    "\n",
    "The FP ideas that have leaked into mainstream programming over the past 20 years: `map`/`filter`/`reduce`, `lambda` expressions, immutable data structures, `list comprehensions`, pipelines; all trace back to functional languages. Even Java and C++ have absorbed them. Understanding FP conceptually makes you better at Python even if you never write a line of Haskell, because you start to recognize when a pure function + transformation pipeline is cleaner than a loop with mutation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8277fb35",
   "metadata": {},
   "source": [
    "**Benefits of functional programming**:\n",
    "\n",
    "- Easier testing and maintenance: Pure functions depend only on their inputs, simplifying testing.\n",
    "- Reduced side effects: By eliminating hidden state changes, debugging becomes more straightforward.\n",
    "- Easier reasoning about concurrent work: Workers can share immutable data without coordinating changes to that data. Other shared mutable state or resources can still require synchronization; immutable inputs alone do not make a whole program free of race conditions.\n",
    "- Improved modularity: Reusable components are easier to build and combine.\n",
    "\n",
    "**Drawbacks of functional programming**:\n",
    "- Steep learning curve: thinking in terms of immutability, higher-order functions, and recursion instead of loops takes practice.\n",
    "- Performance concerns: Immutability can cause high memory usage due to frequent creation of new objects, which may impact performance in resource-constrained systems.\n",
    "- Recursion overhead: purely functional languages replace loops with recursion. Python limits recursion depth (about 1000 calls by default) and does not optimize tail calls, so deep recursion raises `RecursionError`. In Python, a loop is usually the better choice for long sequences."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cef41405",
   "metadata": {},
   "source": [
    "The two paradigms differ in where they put the center of a program. The table summarizes the contrast. It reflects typical emphasis, not a strict boundary, since Python lets you mix both. Recursion is the classic functional way to repeat work, but Python limits recursion depth (see the drawbacks above), so in Python the practical functional tools are comprehensions and higher-order functions such as `map()` and `filter()`.\n",
    "\n",
    ":::{table}\n",
    ":class: comparison-table\n",
    ":widths: auto\n",
    "| Feature | Functional Programming (FP) | Object-Oriented Programming (OOP) |\n",
    "|---|---|---|\n",
    "| Core element | Pure functions | Objects and classes |\n",
    "| State handling | **Immutability:** state is not modified; a new copy is returned. | **Mutability:** objects own and modify their internal data directly. |\n",
    "| Programming model | **Declarative:** focuses on *what* to solve (rooted in lambda calculus, explained under Functions as Values). | **Imperative:** focuses on *how* to solve through step-by-step state changes. |\n",
    "| Execution flow | Recursion and higher-order pipeline composition (`map`, `filter`, `reduce`). | Loops (`for`, `while`) and ordered method calls on objects. |\n",
    "| Strengths | Predictable logic that is easy to test, and safer sharing of data across concurrent work. | Modeling complex real-world entities, user interfaces, and domain boundaries. |\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-gradebook-example",
   "metadata": {},
   "source": [
    "The paradigm table describes the contrast in general. A gradebook program shows how the two approaches work together: a gradebook object manages student records, while pure functions calculate averages, curve scores, and produce rankings. Its methods can call those functions and update stored records when needed. The table follows this example through four design concerns:\n",
    "\n",
    ":::{table}\n",
    ":class: comparison-table\n",
    ":widths: auto\n",
    "| Design concern | OOP contribution | FP contribution |\n",
    "|---|---|---|\n",
    "| Represent students and their grades | Objects maintain related data and enforce rules. | Functions consume well-defined records. |\n",
    "| Calculate curved grades or rankings | Methods expose these operations through an interface. | Pure functions perform calculations without changing the original grades. |\n",
    "| Record a grade change | An explicit method updates the gradebook. | A transformation can first calculate the proposed new values. |\n",
    "| Test the program | Check object behavior and valid state transitions. | Check calculations directly from inputs and expected outputs. |\n",
    ":::\n",
    "\n",
    "The columns describe complementary contributions. OOP methods can return new values without changing state, and functional calculations can work with objects as inputs. In the gradebook design, methods control updates while pure helpers calculate results. Separating those responsibilities lets you test a calculation without setting up the entire gradebook.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9380125",
   "metadata": {},
   "source": [
    "Python is not a purely functional language. It is multi-paradigm: you can write imperative code, object-oriented code, and functional-style code in the same program. In practice, Python's functional tools are most useful when they make **data transformations** clearer, reduce hidden side effects, or let you reuse behavior through functions.\n",
    "\n",
    "These ideas are not just theory. They explain directly why Python features such as **comprehensions**, **`map()`**, **`filter()`**, **`sorted(key=...)`**, **decorators**, and **`functools`** are useful.\n",
    "\n",
    "The goal is not to make Python look like a different language. **The goal is to write transformations that are easy to test, easy to reason about, and hard to accidentally break with hidden shared state.**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98178000",
   "metadata": {},
   "source": [
    "## Purity & Immutability\n",
    "\n",
    "Two ideas sit at the center of functional programming. **Purity** means a function's result depends only on its inputs and the function changes nothing outside itself. **Immutability** means creating new values instead of modifying existing ones. Together they make code easier to test and to reason about."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6cc76d6",
   "metadata": {},
   "source": [
    "### Pure functions\n",
    "\n",
    "A **pure function** has two properties:\n",
    "1. **Deterministic**: given the same inputs, it always returns the same output\n",
    "2. **No side effects**: it doesn't change anything outside itself (e.g., it does not reassign a global variable, mutate an argument, print, or write to a file)\n",
    "\n",
    "These two properties together mean you can understand a pure function in complete *isolation*. You don't need to know the history of the program, what other functions have run, or what global state looks like. The function is a black box: inputs in, output out, nothing else changes. This makes pure functions:\n",
    "- **Easy to test**: just call the function with inputs and check the output; no setup or teardown needed\n",
    "- **Easy to reason about**: you can read the function body without tracking down every variable it might touch\n",
    "- **Safe to reuse**: calling the function twice won't produce different results or corrupt shared state"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d6cc76d6",
   "metadata": {},
   "source": [
    "```{index} pure function, side effect\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9065e2e3",
   "metadata": {},
   "source": [
    "### Immutability\n",
    "\n",
    "**Immutability** means producing new values instead of modifying existing ones. For example, rather than changing a list in place, you return a new list with the change applied.\n",
    "\n",
    "This matters because Python passes a function a reference to the same object, not a copy. When you pass a list to a function and the function calls `.append()` on it, the caller's list changes too, because both names refer to one list object. This is a common source of bugs that can be hard to track down.\n",
    "\n",
    "The fix is simple: instead of mutating, return something new. `lst + [x]` creates a new list. `{**d, 'key': val}` creates a new dictionary. The original is untouched.\n",
    "\n",
    "Python already builds this idea into some types. Tuples, strings, and frozensets are **immutable**: they have no method that changes them in place, so every operation returns a new value. `(1, 2) + (3,)` builds a new tuple, and `'ada'.upper()` returns a new string while `'ada'` is unchanged. Lists, dictionaries, and sets are **mutable**, which is why the bugs in this section involve them. Choosing an immutable type for data that should not change makes accidental mutation impossible instead of merely unlikely.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9065e2e3",
   "metadata": {},
   "source": [
    "```{index} immutability, impure function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8c1a16e",
   "metadata": {},
   "source": [
    "An **impure** function mutates the list passed in — the caller's list is silently changed.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "deb49b04",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 0]\n"
     ]
    }
   ],
   "source": [
    "def append_zero_impure(lst):\n",
    "    lst.append(0)               ### modifies the input list, which is a side effect\n",
    "    return lst\n",
    "\n",
    "data = [1, 2, 3]\n",
    "append_zero_impure(data)\n",
    "print(data)                     ### [1, 2, 3, 0]  ← original changed, even though we didn't ask for it\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55c24dee",
   "metadata": {},
   "source": [
    "A **pure function** returns a new list — the original is untouched.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "295859db",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3]\n",
      "[1, 2, 3, 0]\n"
     ]
    }
   ],
   "source": [
    "def append_zero_pure(lst):\n",
    "    return lst + [0]\n",
    "\n",
    "data = [1, 2, 3]\n",
    "result = append_zero_pure(data)\n",
    "\n",
    "print(data)           # [1, 2, 3] -> original data unchanged\n",
    "print(result)         # [1, 2, 3, 0]\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "991950f9",
   "metadata": {},
   "source": [
    "The same idea applies to dictionaries. In the following example, the dictionary unpacking operator **\\*\\*** creates a new dictionary by copying the key-value pairs from the original. The original settings dictionary remains unchanged, and we get a new dictionary with the updated theme."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2d7c11a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'theme': 'light', 'font_size': 12}\n",
      "{'theme': 'dark', 'font_size': 12}\n"
     ]
    }
   ],
   "source": [
    "settings = {'theme': 'light', 'font_size': 12}\n",
    "\n",
    "### {**settings, ...} copies the pairs into a new dictionary; later keys override earlier ones\n",
    "updated_settings = {**settings, 'theme': 'dark', 'font_size': 14}\n",
    "\n",
    "print(settings)         # {'theme': 'light', 'font_size': 12}   settings is unchanged\n",
    "print(updated_settings) # {'theme': 'dark', 'font_size': 14}\n",
    "\n",
    "### by contrast, these two statements change the dictionary in place, which is a side effect\n",
    "prefs = {'theme': 'light', 'font_size': 12}\n",
    "prefs['theme'] = 'dark'\n",
    "prefs.update({'font_size': 14})\n",
    "print(prefs)            # {'theme': 'dark', 'font_size': 14}   the original values are gone"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d9c5f6d",
   "metadata": {},
   "source": [
    "In the dictionary example above we see that:\n",
    "\n",
    "- **Original State**: `settings` is defined in memory.\n",
    "- **Unpacking**: `{**settings, ...}` copies the key-value pairs from the original dictionary into a **new** one.\n",
    "- **Overwriting**: By placing `'theme': 'dark'` after the unpacking, you tell Python to use the new value if the key already exists.\n",
    "- **Purity**: The original settings remains untouched, preventing side effects in other parts of your program that might be relying on those original values."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dict-update-comparison",
   "metadata": {},
   "source": [
    "| Method | Modifies Original? | Good For... |\n",
    "| --- | --- | --- |\n",
    "| `{**dict, ...}` | No (creates a shallow copy) | Functional programming, preserving original state. |\n",
    "| `.update()` | Yes | Updating multiple keys at the same time in place. |\n",
    "| `dict[key] = value` | Yes | Updating or adding a single key quickly. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-shallow-md",
   "metadata": {},
   "source": [
    "Both `lst + [x]` and `{**d, ...}` make **shallow** copies: the new container is separate, but any nested lists or dictionaries inside it are still the same objects. Changing a nested value through the copy changes the original too. To keep the original untouched, build a new nested value as well:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-shallow-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {'name': 'demo', 'tags': ['a', 'b']}\n",
    "print(config)\n",
    "\n",
    "shallow = {**config, 'name': 'copy'}\n",
    "print(shallow)\n",
    "shallow['tags'].append('c')             # the inner list is shared with config\n",
    "# print(config['tags'])                   # ['a', 'b', 'c']   the original changed\n",
    "print(shallow)\n",
    "print(config)\n",
    "\n",
    "print()\n",
    "\n",
    "config = {'name': 'demo', 'tags': ['a', 'b']}\n",
    "pure = {**config, 'tags': config['tags'] + ['c']}   # a new inner list as well\n",
    "print(pure['tags'])                     # ['a', 'b', 'c']\n",
    "print(config['tags'])                   # ['a', 'b']   unchanged\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-pure-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Pure or Impure?\n",
    "#   Complete the work area below `data`; leave f1 through f5 unchanged.\n",
    "#   1. Replace each empty string in `answers` with 'pure' or 'impure'.\n",
    "#      Classify what each function does when called with numbers (f1, f2),\n",
    "#      a list of numbers (f3, f4), or a string (f5). Add a short comment\n",
    "#      beside each entry explaining your choice.\n",
    "#   2. Define `sorted_copy(items)` in the work area. It must return a new\n",
    "#      sorted list of numbers without changing `items` or printing.\n",
    "#   3. Print the result of sorted_copy(data), then print data itself.\n",
    "#      Expected output: [1, 2, 3] on the first line and [3, 1, 2] on the second.\n",
    "total_calls = 0\n",
    "\n",
    "def f1(x):\n",
    "    return x * 2\n",
    "\n",
    "def f2(x):\n",
    "    global total_calls\n",
    "    total_calls += 1\n",
    "    return x * 2\n",
    "\n",
    "def f3(items):\n",
    "    items.sort()\n",
    "    return items\n",
    "\n",
    "def f4(items):\n",
    "    return sorted(items)\n",
    "\n",
    "def f5(name):\n",
    "    print(f\"Hello, {name}\")\n",
    "    return name\n",
    "\n",
    "data = [3, 1, 2]\n",
    "### Your code starts here.\n",
    "answers = {\n",
    "    'f1': '',\n",
    "    'f2': '',\n",
    "    'f3': '',\n",
    "    'f4': '',\n",
    "    'f5': '',\n",
    "}\n",
    "\n",
    "# Define sorted_copy(items) here, then add the two print calls.\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-pure-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "total_calls = 0\n",
    "\n",
    "def f1(x):\n",
    "    return x * 2\n",
    "\n",
    "def f2(x):\n",
    "    global total_calls\n",
    "    total_calls += 1\n",
    "    return x * 2\n",
    "\n",
    "def f3(items):\n",
    "    items.sort()\n",
    "    return items\n",
    "\n",
    "def f4(items):\n",
    "    return sorted(items)\n",
    "\n",
    "def f5(name):\n",
    "    print(f\"Hello, {name}\")\n",
    "    return name\n",
    "\n",
    "data = [3, 1, 2]\n",
    "### Your code starts here.\n",
    "answers = {\n",
    "    'f1': 'pure',       # depends only on x\n",
    "    'f2': 'impure',     # changes the global total_calls\n",
    "    'f3': 'impure',     # sort() changes the caller's list\n",
    "    'f4': 'pure',       # sorted() returns a new list\n",
    "    'f5': 'impure',     # print is output, a side effect\n",
    "}\n",
    "\n",
    "def sorted_copy(items):\n",
    "    return sorted(items)\n",
    "\n",
    "print(sorted_copy(data))    # [1, 2, 3]\n",
    "print(data)                 # [3, 1, 2]   unchanged\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "479bb20f",
   "metadata": {},
   "source": [
    "## Functions as Values\n",
    "\n",
    "```{index} first-class function, lambda expression, lambda calculus, map()\n",
    "```\n",
    "\n",
    "In Python, functions are **first-class values**; they can be assigned to variables, stored in data structures, passed as arguments, and returned from other functions.\n",
    "\n",
    "The cell below shows each ability with an ordinary function. Notice that `square` without parentheses is the function itself, while `square(4)` calls it."
   ]
  },
  {
   "cell_type": "code",
   "id": "fv-first-class-demo",
   "metadata": {},
   "source": [
    "def square(x):\n",
    "    return x * x\n",
    "\n",
    "f = square                                  # assign: no parentheses, so nothing is called yet\n",
    "print(f(4))                                 # 16\n",
    "\n",
    "functions = [square, abs, str]              # store functions in a list\n",
    "print([fn(-3) for fn in functions])         # [9, 3, '-3']\n",
    "\n",
    "print(list(map(square, [1, 2, 3])))         # pass a function as an argument: [1, 4, 9]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fv-lambda",
   "metadata": {},
   "source": [
    "`f = square` copies a reference to the function, not a result, so `f(4)` **runs** `square`. The list holds three different functions that the loop calls in turn, and `map()` receives `square` as an argument and calls it on every item. Everything else in this chapter builds on these three abilities:\n",
    "1. **Assign** a function to a variable. f = square and then f(4).\n",
    "2. **Store** functions in a data structure. functions = [square, abs, str], which the loop calls in turn.\n",
    "3. **Pass** a function as an argument. map(square, [1, 2, 3]).\n",
    "\n",
    "**Lambda expressions** create small anonymous functions in a single line. You first met them in {doc}`4.2 Function Design <../04-functions/0402-function-design>`; here they become the function argument for `map()`, `filter()`, `sorted()`, and `reduce()`. They are most useful as short key functions or callback functions (a callback is a function you hand to another function to call later). A reminder of the syntax:\n",
    "\n",
    "```python\n",
    "# Syntax: \n",
    "lambda arguments: expression\n",
    "\n",
    "# Examples:\n",
    "lambda x: x ** 2                          # one argument\n",
    "lambda x, y: x + y                        # two arguments\n",
    "\n",
    "sorted(words, key=lambda w: len(w))       # typical use: passed straight to another function\n",
    "```\n",
    "\n",
    "The name comes from **lambda calculus**, a formal system from the 1930s in which Alonzo Church expressed all computation by defining and applying anonymous functions, denoted by the Greek letter λ. It is the mathematical root of functional programming, and Python's `lambda` keyword borrows its name.\n",
    "\n",
    "A lambda is meant to be passed directly to another function. If you want a reusable function with a name, PEP 8 recommends `def` rather than assigning a lambda to a variable, because a `def` function has a real name in tracebacks and can have a docstring.\n",
    "\n",
    "Lambdas are commonly used with `map()`, `filter()`, `sorted()`, and `reduce()`. Each of these takes a function as an argument, which makes it a higher-order function (defined in the Higher-Order Functions section below).\n",
    "\n",
    "| Function | Syntax | Description |\n",
    "|---|---|---|\n",
    "| `map()` | `map(function, iterable)` | Applies a function to every item in an iterable |\n",
    "| `filter()` | `filter(function, iterable)` | Keeps only the items that match a condition |\n",
    "| `sorted()` |  `sorted(iterable, key=function)` | Orders items by the value the key function returns for each one |\n",
    "| `reduce()` | `reduce(f, seq)` | Repeatedly combines items into a single value by applying a function cumulatively from left to right: f(f(f(f(1,2),3),4),5) for five items; the optional initializer is explained below |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50bb4742",
   "metadata": {},
   "source": [
    "```{admonition} MapReduce\n",
    ":class: dropdown\n",
    "**MapReduce** is a programming model for processing very large data sets in parallel across a cluster of machines. A *map* phase transforms records into key/value pairs, and a *reduce* phase combines the values that share a key. Google described it in a 2004 paper, and its open-source implementation, Hadoop, made it the dominant big-data model from the late 2000s to the mid-2010s.\n",
    "\n",
    "Newer tools have largely replaced hand-written MapReduce jobs. Apache Spark keeps intermediate results in memory instead of writing every stage to disk, and cloud warehouses such as BigQuery and Snowflake run queries without exposing the model at all. The idea remains in all of them, and it is the same idea as this chapter's `map()` and `reduce()`. Because pure functions share no state, the work can be split across many machines and the results combined.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fda4b8d",
   "metadata": {},
   "source": [
    "Here we see some examples of `map()`, `filter()`, and `sorted()` working with lambda. `map()` and `filter()` return lazy iterators, not lists, so these examples wrap them in `list(...)` to display the values. Choosing a Style explains lazy evaluation in detail.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6be08f1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25]\n",
      "[2, 4]\n",
      "[('Charlie', 78), ('Alice', 85), ('Bob', 90)]\n"
     ]
    }
   ],
   "source": [
    "# Using lambda with map(): apply a function to each item in a list\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "print(map(lambda x: x ** 2, numbers))\n",
    "\n",
    "squared = list(map(lambda x: x ** 2, numbers))\t### map(function, iterable)\n",
    "print(squared)  # [1, 4, 9, 16, 25]             ### function applies to each element of numbers\n",
    "                      ### nowadays list comprehensions are often preferred for\n",
    "                      ### readability, but map with lambda can be concise for simple transformations\n",
    "# Using lambda with filter(): decide which items to keep based on a condition\n",
    "even_numbers = list(filter(lambda x: x % 2 == 0, numbers))  ### filter(function, iterable) keeps only \n",
    "print(even_numbers)  # [2, 4]                               ### elements where the function returns True (even numbers in this case)     \n",
    "\n",
    "# Using lambda with sorted(): sort a list of tuples by a specific element\n",
    "students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]\n",
    "sorted_by_grade = sorted(students, key=lambda student: student[1])  ### key function extracts the grade \n",
    "                                                                    ### (the second element of the tuple) for sorting\n",
    "print(sorted_by_grade)  \t# [('Charlie', 78), ('Alice', 85), ('Bob', 90)]\n",
    "### the same as:\n",
    "def get_grade(student):\n",
    "    return student[1]\n",
    "\n",
    "sorted(students, key=get_grade)   # no parentheses: passes the function itself"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-tuple-key-md",
   "metadata": {},
   "source": [
    "A key function can also return a tuple. Python compares tuples item by item, so `sorted()` orders the records by the first item of the key and uses the next item only to break ties. To sort a numeric field in descending order while the other fields stay ascending, negate that number in the key: a larger score becomes a smaller negative number, so it comes first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ch10-tuple-key-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Dan', 92, 'A'), ('Bob', 90, 'A'), ('Alice', 85, 'B'), ('Cara', 78, 'B')]\n"
     ]
    }
   ],
   "source": [
    "records = [('Alice', 85, 'B'), ('Bob', 90, 'A'), ('Cara', 78, 'B'), ('Dan', 92, 'A')]\n",
    "\n",
    "# Sort by section (index 2) ascending, then by score (index 1) descending\n",
    "ranked = sorted(records, key=lambda s: (s[2], -s[1]))\n",
    "print(ranked)  # [('Dan', 92, 'A'), ('Bob', 90, 'A'), ('Alice', 85, 'B'), ('Cara', 78, 'B')]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5ae1a45",
   "metadata": {},
   "source": [
    "With `reduce()`, you have to import `reduce` from `functools` first. When you do not pass an initial value, the accumulator starts as the first element of the iterable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4dc18f72",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n",
      "120\n"
     ]
    }
   ],
   "source": [
    "from functools import reduce\n",
    "\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "\n",
    "# reduce(f, seq) applies f cumulatively: f(f(f(f(1,2),3),4),5)\n",
    "total = reduce(lambda acc, x: acc + x, numbers) ### acc == accumulator, x == current element\n",
    "print(total)   # 15\n",
    "\n",
    "product = reduce(lambda acc, x: acc * x, numbers)   # acc starts at 1 and multiplies each number in the list\n",
    "print(product) # 120"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-reduce-initializer",
   "metadata": {},
   "source": [
    "**The initializer.** `reduce()` takes an optional third argument, the **initializer**: `reduce(f, seq, initial)`. When you pass it, the accumulator starts at `initial`, and the function is applied to every item in the sequence, starting with the first:\n",
    "\n",
    "`reduce(f, [a, b, c], initial)` computes `f(f(f(initial, a), b), c)`\n",
    "\n",
    "You need an initializer in two situations:\n",
    "\n",
    "- **The items are a different kind of value than the result.** To total the grades in a list of `(name, grade)` tuples, the accumulator is a number but each item is a tuple. Without an initializer, the first tuple becomes the starting accumulator, and `acc + s[1]` then tries to add an integer to a tuple.\n",
    "- **The sequence might be empty.** With no items and no initializer, `reduce()` has nothing to return and raises `TypeError`. With an initializer, it returns the initializer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-reduce-initializer-index",
   "metadata": {},
   "source": [
    "```{index} reduce() initializer\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-reduce-initializer-example",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "253\n",
      "TypeError: can only concatenate tuple (not \"int\") to tuple\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "from functools import reduce\n",
    "\n",
    "students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]\n",
    "\n",
    "### initializer 0: acc starts at 0, and every tuple is passed in as s\n",
    "total = reduce(lambda acc, s: acc + s[1], students, 0)\n",
    "print(total)    # 253\n",
    "\n",
    "### without an initializer, acc starts as the first tuple ('Alice', 85)\n",
    "try:\n",
    "    reduce(lambda acc, s: acc + s[1], students)\n",
    "except TypeError as e:\n",
    "    print(\"TypeError:\", e)\n",
    "\n",
    "### an empty sequence returns the initializer\n",
    "print(reduce(lambda acc, x: acc + x, [], 0))    # 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53c780b6",
   "metadata": {},
   "source": [
    "Modern Python often prefers clearer built-in alternatives for common cases:\n",
    "\n",
    "- `sum()` instead of `reduce()` for addition\n",
    "- `max()` and `min()` instead of `reduce()` for extremes\n",
    "- `any()` and `all()` instead of `reduce()` for yes/no questions about a collection\n",
    "- a loop or a comprehension when the steps are easy to read\n",
    "\n",
    "`reduce()` can be harder to read for complex logic, so reach for it only when there is genuinely no built-in equivalent. Custom accumulations are where `reduce()` starts to earn its place."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "reducers-anyall-md",
   "metadata": {},
   "source": [
    "`any()` returns `True` if at least one item is true, and `all()` returns `True` only if every item is true. Both stop as soon as the answer is known: `any()` stops at the first true item, and `all()` stops at the first false one. They pair with `map()` or a comprehension that produces the true/false values:"
   ]
  },
  {
   "cell_type": "code",
   "id": "reducers-anyall-code",
   "metadata": {},
   "source": [
    "grades = [85, 90, 78, 98]\n",
    "\n",
    "print(sum(grades), max(grades), min(grades))        # 351 98 78\n",
    "\n",
    "print(any([g < 80 for g in grades]))                # True: 78 is below 80\n",
    "print(all([g >= 70 for g in grades]))               # True: every grade is at least 70\n",
    "print(any(map(lambda g: g > 100, grades)))          # False: no grade is above 100\n",
    "\n",
    "# The same question as a fold works, but it is longer and always visits every item\n",
    "print(reduce(lambda found, g: found or g < 80, grades, False))      # True"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "operator-md",
   "metadata": {},
   "source": [
    "**The `operator` module.** Small lambdas such as `lambda s: s[1]` or `lambda a, b: a + b` appear so often that the standard library provides them as ready-made functions in `operator`. \n",
    "\n",
    "- `itemgetter(1)` is the function `lambda s: s[1]`, and `itemgetter(2, 1)` returns a tuple of two fields. \n",
    "- `attrgetter('grade')` reads an attribute from an object. \n",
    "- `operator.add` and `operator.mul` are the `+` and `*` operators as functions. \n",
    "\n",
    "They read more clearly than the equivalent lambdas and run faster, so reach for them when the lambda only picks a field or applies one operator."
   ]
  },
  {
   "cell_type": "code",
   "id": "operator-code",
   "metadata": {},
   "source": [
    "from operator import itemgetter, attrgetter, add, mul\n",
    "\n",
    "students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]\n",
    "\n",
    "print(sorted(students, key=itemgetter(1)))          # same as key=lambda s: s[1]\n",
    "print(list(map(itemgetter(0), students)))           # ['Alice', 'Bob', 'Charlie']\n",
    "\n",
    "class Student:\n",
    "    def __init__(self, name, grade):\n",
    "        self.name = name\n",
    "        self.grade = grade\n",
    "\n",
    "roster = [Student('Alice', 85), Student('Bob', 90), Student('Charlie', 78)]\n",
    "best = max(roster, key=attrgetter('grade'))         # same as key=lambda s: s.grade\n",
    "print(best.name)                                    # Bob\n",
    "\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "print(reduce(add, numbers), reduce(mul, numbers))   # 15 120: no lambda needed"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-reduce-init-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: reduce() and the Initializer\n",
    "#   Use reduce() with an initializer for each task below.\n",
    "#   1. Total the quantities in `orders`, a list of (fruit, quantity) tuples, and print the total.\n",
    "#   2. Make the same call without the initializer inside try/except TypeError,\n",
    "#      and print \"TypeError\" when it fails.\n",
    "#   3. Run the call with the initializer on an empty list, `[]`, and print the result.\n",
    "#   4. Build the dictionary {fruit: quantity} from `orders` with a dictionary initializer.\n",
    "#      Each step must return a new dictionary, `{**acc, fruit: quantity}`, not change one in place.\n",
    "#      Print the dictionary.\n",
    "#   Print exactly:\n",
    "#   10\n",
    "#   TypeError\n",
    "#   0\n",
    "#   {'apple': 3, 'pear': 2, 'kiwi': 5}\n",
    "from functools import reduce\n",
    "\n",
    "orders = [('apple', 3), ('pear', 2), ('kiwi', 5)]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-reduce-init-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "TypeError\n",
      "0\n",
      "{'apple': 3, 'pear': 2, 'kiwi': 5}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from functools import reduce\n",
    "\n",
    "orders = [('apple', 3), ('pear', 2), ('kiwi', 5)]\n",
    "\n",
    "# 1. The items are tuples but the result is a number, so the accumulator must start at 0.\n",
    "total = reduce(lambda acc, order: acc + order[1], orders, 0)\n",
    "print(total)    # 10\n",
    "\n",
    "# 2. Without an initializer, acc starts as ('apple', 3), and acc + order[1] adds an int to a tuple.\n",
    "try:\n",
    "    reduce(lambda acc, order: acc + order[1], orders)\n",
    "except TypeError:\n",
    "    print(\"TypeError\")\n",
    "\n",
    "# 3. An empty sequence returns the initializer instead of raising TypeError.\n",
    "print(reduce(lambda acc, order: acc + order[1], [], 0))     # 0\n",
    "\n",
    "# 4. A dictionary initializer; each step returns a new dictionary.\n",
    "stock = reduce(lambda acc, order: {**acc, order[0]: order[1]}, orders, {})\n",
    "print(stock)    # {'apple': 3, 'pear': 2, 'kiwi': 5}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc0202cc",
   "metadata": {},
   "source": [
    "## Higher-Order Functions\n",
    "\n",
    "A **higher-order function** is a function that either accepts a function as an argument or returns a function as its result. Python's built-in higher-order functions are: \n",
    "- `map(f, iter)`, \n",
    "- `filter(f, iter)`, \n",
    "- `sorted(iter, key=f)`, \n",
    "- `min(iter, key=f)`/`max(iter, key=f)`, and \n",
    "- `any(iter)`/`all(iter)` . \n",
    "\n",
    "The standard library's `functools` module is specifically dedicated to higher-order functions and operations on callables, and `reduce()` is one of them.\n",
    " \n",
    "**Decorators** are a Python idiom built entirely on this idea: a decorator is a higher-order function that takes a function and returns an enhanced version of it.\n",
    "\n",
    "You can write your own higher-order functions:\n",
    "\n",
    "\n",
    "```python\n",
    "def apply(func, x): \n",
    "    return func(x)\n",
    "\n",
    "def square(n):\n",
    "    return n **2 \n",
    "\n",
    "print(apply(square, 7)).        ### 49\n",
    "```\n",
    "\n",
    "Or, with `lambda`:\n",
    "\n",
    "```python\n",
    "def apply_twice(f, x):\n",
    "    return f(f(x))\n",
    "\n",
    "apply_twice(lambda x: x + 3, 10)  ### 16; we pass a lambda function as an argument\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-hof-md",
   "metadata": {},
   "source": [
    "Because functions are values, a function can be stored in a variable or a dictionary and passed like any other object. In `apply_twice(f, x)` above, the parameter `f` holds a function, and `f(f(x))` calls it twice. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73ba4ee9-2d84-437b-b01b-dc20ca3821b2",
   "metadata": {},
   "source": [
    "Trace `apply_twice(double, 3)` with `double(x)` below: the first call gives `double(3) = 6`, and the second gives `double(6) = 12`.\n",
    "\n",
    "Pass the function itself, as in `apply_twice(double, 3)`. If you write `apply_twice(double(2), 3)`, you first call `double(2)`, and the number `4` that comes back is not a function, so `f(x)` inside `apply_twice` will raise a `TypeError` reporting that an `int` object is not callable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-hof-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(x):\n",
    "    return x * 2\n",
    "\n",
    "def negate(x):\n",
    "    return -x\n",
    "\n",
    "operations = {'double': double, 'negate': negate}   # functions stored in a dictionary\n",
    "for name, op in operations.items():\n",
    "    print(name, op(7))                              # double 14, negate -7\n",
    "\n",
    "def apply_twice(f, x):\n",
    "    return f(f(x))\n",
    "\n",
    "print(apply_twice(double, 3))                       # 12\n",
    "print(apply_twice(lambda s: s + '!', 'hi'))         # hi!!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-closures",
   "metadata": {},
   "source": [
    "### Closures\n",
    "\n",
    "A higher-order function can also *return* a function. In {doc}`4.2 Function Design <../04-functions/0402-function-design>`, you saw that a function returned this way is a **closure**. The name comes from the mathematical concept of an operation being \"closed\" within an environment, meaning the function is packaged with its environment to form a self-contained, complete entity.\n",
    "\n",
    "A closure remembers values from the scope where it was created. This provides a clean way to attach state to a function without relying on global variables or creating a full **class**.\n",
    "\n",
    "Closures pair naturally with `map()`, `filter()`, and `sorted()`, because a function factory can build exactly the function argument those calls need:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-closures-index",
   "metadata": {},
   "source": [
    "```{index} closure\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-closure-lambda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[90, 95, 83, 100]\n",
      "[95, 100, 88, 100]\n"
     ]
    }
   ],
   "source": [
    "def make_curve(points):\n",
    "    return lambda grade: min(grade + points, 100)   ### closure over points; \n",
    "                                                    ### returns a lambda function\n",
    "\n",
    "grades = [85, 90, 78, 98]\n",
    "\n",
    "print(list(map(make_curve(5), grades)))     # [90, 95, 83, 100]\n",
    "print(list(map(make_curve(10), grades)))    # [95, 100, 88, 100]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-closure-md",
   "metadata": {},
   "source": [
    "Each call to `make_curve` creates its own `points` and its own returned function, so `curve5` and `curve10` below do not affect each other. A function object keeps the values it remembers in `__closure__`, which you can inspect (an optional look under the hood). **Predict** what the first `print` shows before you run the cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-closure-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "curve5 = make_curve(5)\n",
    "curve10 = make_curve(10)\n",
    "\n",
    "print(curve5(90), curve10(90))             # 95 100\n",
    "print(curve5.__closure__[0].cell_contents) # 5, value remembered from make_curve(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "late-binding-md",
   "metadata": {},
   "source": [
    "A **closure trap** (late binding). A closure trap occurs because Python looks up variables in outer scopes at execution time, not at definition time. A closure remembers the *variable*, not the value the variable had when the function was created. The variable is looked up when the function is *called*. In the next cell, three lambdas are built in a loop. The closure trap is important because it is one of the most common, silent, and frustrating bugs in Python and frequently breaks UI elements.\n",
    "\n",
    "Now, **predict** the printed list before you run it. Imagine that you have 3 buttons to control separately, and they show the same behavior at the same time. "
   ]
  },
  {
   "cell_type": "code",
   "id": "late-binding-code",
   "metadata": {},
   "source": [
    "funcs = [lambda x: x * i for i in range(3)]\n",
    "print([f(10) for f in funcs])           # [20, 20, 20], not [0, 10, 20]\n",
    "\n",
    "### check\n",
    "print()\n",
    "for idx, f in enumerate(funcs):\n",
    "    # Read the live value inside the closure cell\n",
    "    captured_i = f.__closure__[0].cell_contents\n",
    "    print(f\"Lambda {idx} -> memory: {f} | captured 'i': {captured_i}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "late-binding-md2",
   "metadata": {},
   "source": [
    "All three lambdas share one `i`. By the time they are called, the loop has finished and `i` is `2`, so each computes `x * 2`. Two fixes give each function its own value. A default argument captures the value at creation time, because defaults are evaluated once, when the lambda is defined. A function factory such as `make_curve` does the same by giving each call its own `points`."
   ]
  },
  {
   "cell_type": "code",
   "id": "late-binding-code2",
   "metadata": {},
   "source": [
    "### Default arguments: early binding (evaluating the value immediately during the loop).\n",
    "funcs = [lambda x, i=i: x * i for i in range(3)]        # fix 1: i=i captures the current value\n",
    "print([f(10) for f in funcs])                           # [0, 10, 20]\n",
    "\n",
    "\n",
    "### Factory Function: creates a new intermediate scope/closure cell \n",
    "### for every single iteration.\n",
    "def make_multiplier(n):                                 # fix 2: a factory gives each function its own n\n",
    "    return lambda x: x * n\n",
    "\n",
    "funcs = [make_multiplier(i) for i in range(3)]\n",
    "print([f(10) for f in funcs])                           # [0, 10, 20]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ch10-closure-decorator-link",
   "metadata": {},
   "source": [
    "Decorators, covered next, are built on closures: the `wrapper` function inside a decorator is a closure that remembers the original `func`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-closure-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Closures\n",
    "#   1. Write `make_tax(rate)` that returns a function. The returned function takes\n",
    "#      a price and returns the price with tax added, rounded to 2 decimal places.\n",
    "#      Define the returned function with `def` inside `make_tax`.\n",
    "#   2. Create `tax5 = make_tax(0.05)` and `tax10 = make_tax(0.10)`.\n",
    "#   3. Use map() with tax5 to add 5% tax to every price in `prices`, and print the list.\n",
    "#      Expected output: [4.2, 12.6, 8.4, 21.0]\n",
    "#   4. Print tax10(20.0) and then tax5(20.0) to show that each closure keeps its own rate.\n",
    "#      Expected output: 22.0 and then 21.0\n",
    "prices = [4.0, 12.0, 8.0, 20.0]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-closure-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "prices = [4.0, 12.0, 8.0, 20.0]\n",
    "\n",
    "def make_tax(rate):\n",
    "    def add_tax(price):\n",
    "        return round(price * (1 + rate), 2)     # rate is remembered from make_tax\n",
    "    return add_tax\n",
    "\n",
    "tax5 = make_tax(0.05)\n",
    "tax10 = make_tax(0.10)\n",
    "\n",
    "print(list(map(tax5, prices)))      # [4.2, 12.6, 8.4, 21.0]\n",
    "print(tax10(20.0))                  # 22.0\n",
    "print(tax5(20.0))                   # 21.0, tax5 still remembers 0.05\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "793c5539-e20d-470f-b47d-8d6a1632f01f",
   "metadata": {},
   "source": [
    "## Decorators\n",
    "\n",
    "A **decorator** is a higher-order function; it takes a function as input and returns a modified version without modifying the original function . The `@decorator_name` syntax is Python's shorthand for `func = decorator(func)`, making it easy to add cross-cutting behavior (e.g., logging, timing, validation, error handling, and authentication that span across an  application but not part of the core business logic) without changing the original function's code.\n",
    "\n",
    "**How decorators work:**\n",
    "1. They take a function as input\n",
    "2. Wrap it in a new function that adds behavior\n",
    "3. Return the wrapper, applied automatically with `@decorator_name`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-793c5539-e20d-470f-b",
   "metadata": {},
   "source": [
    "```{index} decorator (@), wrapper function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d01c7226",
   "metadata": {},
   "source": [
    "The next example builds a basic decorator and applies it with `@`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "233f2bd2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Something before the function\n",
      "Hello!\n",
      "Something after the function\n",
      "say_hello - Print a greeting.\n"
     ]
    }
   ],
   "source": [
    "# Basic decorator example\n",
    "import functools\n",
    "\n",
    "def my_decorator(func):     ### the decorator takes the original function as its argument\n",
    "    @functools.wraps(func)  ### copies func's name and docstring onto wrapper\n",
    "    def wrapper():          ### wrapper is a closure: it remembers func\n",
    "        print(\"Something before the function\")\n",
    "        result = func()     ### calls the original function and stores its result\n",
    "        print(\"Something after the function\")\n",
    "        return result\n",
    "    return wrapper          ### the decorator returns wrapper, which replaces say_hello\n",
    "\n",
    "@my_decorator               ### same as say_hello = my_decorator(say_hello)\n",
    "def say_hello():\n",
    "    \"\"\"Print a greeting.\"\"\"\n",
    "    print(\"Hello!\")\n",
    "\n",
    "say_hello()\n",
    "\n",
    "print(say_hello.__name__, \"-\", say_hello.__doc__)   ### metadata kept by @wraps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-wraps-md",
   "metadata": {},
   "source": [
    "The last line shows what `@wraps(func)` does. After decoration, the name `say_hello` refers to `wrapper`, so without `@wraps` the line would print `wrapper - None`. With it, `wrapper` carries the original name and docstring, so inspecting `say_hello.__name__` or using `help(say_hello)` identifies the original function. This preserves metadata; it does not rename the wrapper's executing code frame. A traceback can still show a frame named `wrapper`.\n",
    "\n",
    "The decorated `say_hello` is impure: it prints both the wrapper's messages and the greeting. A decorator can organize useful side effects without removing them. The wrapper is a closure because it remembers `func`; that describes its structure, not its purity.\n",
    "\n",
    "The `wrapper` above takes no arguments, so it only works for functions that take none. To decorate any function, give the wrapper `*args` and `**kwargs` and pass them through unchanged to `func`, as the timer decorator below does."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e83a2f69",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "slow_add took 0.5013 seconds\n",
      "5\n",
      "slow_add took 0.1050 seconds\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "# A decorator that works with any arguments\n",
    "from functools import wraps\n",
    "from time import perf_counter, sleep\n",
    "\n",
    "def timer_decorator(func):\n",
    "    @wraps(func)                        ### preserves func's name and docstring\n",
    "    def wrapper(*args, **kwargs):       ### accepts any positional and keyword arguments\n",
    "        start_time = perf_counter()\n",
    "        result = func(*args, **kwargs)  ### passes them unchanged to the original function\n",
    "        end_time = perf_counter()\n",
    "        print(f\"{func.__name__} took {end_time - start_time:.4f} seconds\")\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@timer_decorator                        ### same as slow_add = timer_decorator(slow_add)\n",
    "def slow_add(a, b, delay=0.5):\n",
    "    sleep(delay)                        ### doing something\n",
    "    return a + b\n",
    "\n",
    "print(slow_add(2, 3))                   ### positional arguments reach slow_add through *args\n",
    "print(slow_add(2, 3, delay=0.1))        ### keyword arguments reach it through **kwargs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-deco-steps-md",
   "metadata": {},
   "source": [
    "The `@` line is only shorthand. Writing the assignment yourself shows the three steps: define `greet`, pass it to `shout`, and rebind the name `greet` to the wrapper that comes back."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-deco-steps-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import wraps\n",
    "\n",
    "def shout(func):\n",
    "    @wraps(func)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        return func(*args, **kwargs).upper()    # change the result on the way out\n",
    "    return wrapper\n",
    "\n",
    "def greet(name):\n",
    "    return f\"hello, {name}\"\n",
    "\n",
    "greet = shout(greet)            # exactly what @shout above def greet would do\n",
    "print(greet(\"ada\"))             # HELLO, ADA\n",
    "print(greet.__name__)           # greet, kept by @wraps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-decorator-purity-md",
   "metadata": {},
   "source": [
    "**Classify behavior, not syntax.** The timer adds clock readings and printing, while `shout` only transforms the value returned by its wrapped function. Assuming the functions and inputs shown above, their behavior differs:\n",
    "\n",
    "| Call | Pure or impure? | Reason |\n",
    "|---|---|---|\n",
    "| `apply_twice(double, 3)` | Pure | `double` only computes from its argument, and `apply_twice` adds no side effects. |\n",
    "| Decorated `say_hello()` | Impure | The wrapper and original function print. |\n",
    "| Decorated `slow_add(2, 3)` | Impure | It waits, reads a clock, and prints a timing message, even though the returned sum stays the same. |\n",
    "| `greet(\"ada\")` after `greet = shout(greet)` | Pure | The original function constructs a string and the wrapper returns a new uppercase string; neither changes external state. |\n",
    "\n",
    "The `print(greet(\"ada\"))` demonstration performs output in the calling code. That does not make `greet` impure: inspect what happens *inside* the function call, including any functions it calls. Conversely, returning a predictable value does not make a function pure if it also prints or changes external state.\n",
    "\n",
    "**Question.** Suppose `double` is changed to print `x` before returning `x * 2`. Would `apply_twice(double, 3)` still return `12`? Would it still be pure? Explain before opening the feedback.\n",
    "\n",
    "```{admonition} Check your reasoning\n",
    ":class: dropdown\n",
    "It still returns `12`, but it prints `3` during the inner call and `6` during the outer call. The computation is now impure because of those side effects. `apply_twice` did not change: its behavior depends on the function passed to it. A useful design is to keep the calculation pure and put logging or display at a deliberate boundary, such as the calling code or an explicitly side-effecting wrapper.\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-deco-stack-md",
   "metadata": {},
   "source": [
    "**Stacking decorators.** More than one decorator can sit above a function. They are applied from the bottom up, so the decorator nearest the function wraps it first and the one above wraps that result:\n",
    "\n",
    "`@bold` above `@italic` above `def label` means `label = bold(italic(label))`. A call therefore runs `bold`'s wrapper first, which calls `italic`'s wrapper, which calls the original."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-deco-stack-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bold(func):\n",
    "    @wraps(func)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        return f\"<b>{func(*args, **kwargs)}</b>\"\n",
    "    return wrapper\n",
    "\n",
    "def italic(func):\n",
    "    @wraps(func)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        return f\"<i>{func(*args, **kwargs)}</i>\"\n",
    "    return wrapper\n",
    "\n",
    "@bold\n",
    "@italic\n",
    "def label(text):\n",
    "    return text\n",
    "\n",
    "print(label(\"hi\"))              # <b><i>hi</i></b>: italic wraps first, bold wraps that"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-deco-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Write a Decorator\n",
    "#   1. Write a decorator `require_positive` that wraps a function. If any positional\n",
    "#      argument is <= 0, it raises ValueError(\"arguments must be positive\").\n",
    "#      Otherwise it returns the function's result.\n",
    "#      Use @wraps and accept *args and **kwargs.\n",
    "#   2. Apply it with @ to `area(width, height)`, which returns width * height.\n",
    "#   3. Show that area(3, 4) returns 12, and that area(-1, 4) raises the ValueError,\n",
    "#      caught with try/except and printing the message.\n",
    "#   4. Print area.__name__ to show that @wraps kept the original name.\n",
    "#      Expected output: 12, arguments must be positive, area (one per line).\n",
    "from functools import wraps\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-deco-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "from functools import wraps\n",
    "\n",
    "def require_positive(func):\n",
    "    @wraps(func)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        if any(a <= 0 for a in args):\n",
    "            raise ValueError(\"arguments must be positive\")\n",
    "        return func(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "@require_positive\n",
    "def area(width, height):\n",
    "    return width * height\n",
    "\n",
    "print(area(3, 4))               # 12\n",
    "try:\n",
    "    area(-1, 4)\n",
    "except ValueError as error:\n",
    "    print(error)                # arguments must be positive\n",
    "print(area.__name__)            # area, kept by @wraps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee8d5baf-f618-4ac6-b569-a0cd10505810",
   "metadata": {},
   "source": [
    "### Built-in Decorators\n",
    "\n",
    "- `@property`: Creates getter/setter methods\n",
    "- `@staticmethod`: Method doesn't need self or cls (covered in {doc}`9.3 Advanced OOP Topics <../09-oop/0903-oop-advanced>`)\n",
    "- `@classmethod`: Method receives class as first argument (covered in {doc}`9.3 Advanced OOP Topics <../09-oop/0903-oop-advanced>`)\n",
    "\n",
    "`@functools.wraps`, used in the decorators above, is a helper for writing custom decorators. It preserves the wrapped function's name, docstring, and other metadata."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ee8d5baf-f618-4ac6-b",
   "metadata": {},
   "source": [
    "```{index} property decorator (@property), wraps()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-prop-md1",
   "metadata": {},
   "source": [
    "**Review from Chapter 9.** Let's take a look at the `@property` decorator, which you used in {doc}`9.1 OOP Design and Methods <../09-oop/0901-oop-design>` to give read access to an internal attribute. At first glance, `@property` only saves typing: you read the value as an attribute, without parentheses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-prop-code1",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    def __init__(self):\n",
    "        self._balance = 100\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        \"\"\"Current balance in dollars (read-only).\"\"\"\n",
    "        return self._balance\n",
    "\n",
    "acct = BankAccount()\n",
    "print(acct.balance)         # 100"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-prop-md2",
   "metadata": {},
   "source": [
    "The bigger idea is that it turns a method into a *managed attribute*, which means you can:\n",
    "\n",
    "- compute values dynamically\n",
    "- validate data\n",
    "- make attributes read-only\n",
    "- keep internal implementation hidden\n",
    "\n",
    "For example, an area can be computed from the radius every time it is read:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-prop-code2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "class Circle:\n",
    "    def __init__(self, radius):\n",
    "        self.radius = radius\n",
    "\n",
    "    @property\n",
    "    def area(self):\n",
    "        return math.pi * self.radius ** 2\n",
    "\n",
    "c = Circle(5)\n",
    "print(c.area)               # 78.53981633974483\n",
    "c.radius = 10\n",
    "print(c.area)               # 314.1592653589793, recomputed on each read"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-prop-md3",
   "metadata": {},
   "source": [
    "So `@property` does more than hide parentheses: it is a decorator that runs code each time the attribute is read."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-deco-class-md",
   "metadata": {},
   "source": [
    "(Enrichment: optional): \n",
    "\n",
    "**class-based decorators.** A decorator can also be a class. The class's `__init__` receives the function, and `__call__` runs each time the decorated name is called. This is not needed for the rest of the chapter or the assignments. The `CountCalls` example is impure: each call changes the instance's `count` attribute and prints a message."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b24e275",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Call #1 of say_hi\n",
      "Hi there!\n",
      "Call #2 of say_hi\n",
      "Hi there!\n",
      "Call #3 of say_hi\n",
      "Hi there!\n"
     ]
    }
   ],
   "source": [
    "# Class-based decorator\n",
    "class CountCalls:\n",
    "    def __init__(self, func):\n",
    "        self.func = func\n",
    "        self.count = 0\n",
    "    ### __call__ makes an instance of the class behave like a function — it's invoked whenever you call the object with ().\n",
    "    def __call__(self, *args, **kwargs):\n",
    "        self.count += 1\n",
    "        print(f\"Call #{self.count} of {self.func.__name__}\")\n",
    "        return self.func(*args, **kwargs)\n",
    "\n",
    "@CountCalls     ### say_hi = CountCalls(say_hi)  \n",
    "def say_hi():   ### # say_hi is now a CountCalls instance\n",
    "    print(\"Hi there!\")\n",
    "\n",
    "say_hi()        ### triggers __call__\n",
    "say_hi()\n",
    "say_hi()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deco-args-md",
   "metadata": {},
   "source": [
    "**Enrichment (optional): decorators with arguments.** To configure a decorator, as in `@repeat(3)`, add one more layer. `repeat(3)` is an ordinary function call that returns the real decorator, and that decorator then wraps the function. The `@` line is shorthand for `hello = repeat(3)(hello)`. Three functions are nested: the outer one receives the setting (`times`), the middle one receives the function being decorated, and the inner `wrapper` runs on each call. Like the other examples, this decorator is impure because it repeats the function's printing."
   ]
  },
  {
   "cell_type": "code",
   "id": "deco-args-code",
   "metadata": {},
   "source": [
    "from functools import wraps\n",
    "\n",
    "def repeat(times):                      # layer 1: receives the setting\n",
    "    def decorator(func):                # layer 2: receives the function\n",
    "        @wraps(func)\n",
    "        def wrapper(*args, **kwargs):   # layer 3: runs on every call\n",
    "            result = None\n",
    "            for _ in range(times):\n",
    "                result = func(*args, **kwargs)\n",
    "            return result\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "@repeat(3)                              # same as hello = repeat(3)(hello)\n",
    "def hello(name):\n",
    "    print(f\"Hello, {name}!\")\n",
    "\n",
    "hello(\"Ada\")                            # prints the greeting three times"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "b60a322b-5451-4b56-a234-7fa0fec95155",
   "metadata": {},
   "source": [
    "## Comprehensions\n",
    "\n",
    "You already know the comprehension syntax: list comprehensions from {doc}`6.1 Lists <../06-collections/0601-lists>`, dictionary comprehensions from {doc}`7.3 Dictionary Patterns <../07-dictionaries/0703-dict-patterns>`, and set comprehensions from {doc}`7.4 Sets <../07-dictionaries/0704-sets>`. This section looks at comprehensions from the functional side. A comprehension is Python's built-in syntax for the same transform and filter steps that `map()` and `filter()` perform.\n",
    "\n",
    "Each part of a comprehension lines up with one of those functions:\n",
    "\n",
    "| Comprehension part | Functional equivalent | Effect |\n",
    "|---|---|---|\n",
    "| The expression before `for` | `map()` | Transform each item |\n",
    "| The `if` clause after `for` | `filter()` | Keep only the items that pass the test |\n",
    "\n",
    "The code below writes each step both ways. Each pair prints the same result."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-b60a322b-5451-4b56-a",
   "metadata": {},
   "source": [
    "```{index} list comprehension\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "33f29ce6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25, 36]\n",
      "[1, 4, 9, 16, 25, 36]\n",
      "[2, 4, 6]\n",
      "[2, 4, 6]\n",
      "[4, 16, 36]\n",
      "[4, 16, 36]\n"
     ]
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "# Transform: map() vs. the expression part\n",
    "print(list(map(lambda x: x ** 2, numbers)))\n",
    "print([x ** 2 for x in numbers])\n",
    "\n",
    "# Filter: filter() vs. the if clause\n",
    "print(list(filter(lambda x: x % 2 == 0, numbers)))\n",
    "print([x for x in numbers if x % 2 == 0])\n",
    "\n",
    "# Filter, then transform\n",
    "print(list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))))\n",
    "print([x ** 2 for x in numbers if x % 2 == 0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3c1f0d2-comp-map-filter",
   "metadata": {},
   "source": [
    "The last pair shows why comprehensions are usually the Pythonic choice. The nested `map(filter(...))` call reads from the inside out, and it needs two lambdas. The comprehension reads left to right, with no lambdas at all.\n",
    "\n",
    "The position of `if` tells you which operation you are doing. A conditional expression (from {doc}`3.1 Conditionals <../03-control-flow/0301-conditionals>`) in the expression part is still a map: every item produces a result. An `if` clause after `for` is a filter: some items are dropped."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ff6e4576",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 0, 0, 2, 4]\n",
      "[0, 2, 4]\n"
     ]
    }
   ],
   "source": [
    "numbers = [-3, -1, 0, 2, 4]\n",
    "\n",
    "# Map with a conditional expression: every item produces a value\n",
    "print([x if x >= 0 else 0 for x in numbers])\n",
    "\n",
    "# Filter: the negative items are dropped\n",
    "print([x for x in numbers if x >= 0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7e4a9c5-comp-purity",
   "metadata": {},
   "source": [
    "A comprehension is an expression: its job is to build and return a new list, set, or dictionary. Write it the way you write a pure function. Compute each item from the loop data only, with no side effects such as printing, appending to another list, or changing a variable outside the comprehension.\n",
    "\n",
    "Do not use a comprehension only for its side effects. `[print(x) for x in numbers]` prints every number, but it also builds a list of `None` values, one per `print()` call, and then discards it. Writing a comprehension signals that the resulting list matters, so building one that is never used makes the code misleading. In a notebook, the unused list even appears as output: when the comprehension is the last line of a cell, the list of `None` values shows up below the printed numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7e4a9c5-comp-side-effect",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[None, None, None, None, None]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "[print(x) for x in numbers]   # prints, then displays the unused list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7e4a9c5-comp-use-loop",
   "metadata": {},
   "source": [
    "Use a `for` loop instead when the work:\n",
    "\n",
    "- has side effects, such as printing, writing to a file, or updating another collection,\n",
    "- needs more than one statement per item, or\n",
    "- needs to stop early with `break`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-comp-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Rewrite as Comprehensions\n",
    "#   Each expression below uses map() and filter() with lambdas.\n",
    "#   1. Rewrite `discounted` as a list comprehension.\n",
    "#   2. Rewrite `a_names` as a list comprehension.\n",
    "#   3. Rewrite `long_upper` as a single list comprehension.\n",
    "#   4. Print whether each comprehension equals the original (three lines).\n",
    "#   5. Print one line per name saying whether it is a map, a filter, or both.\n",
    "#   Print exactly:\n",
    "#   True\n",
    "#   True\n",
    "#   True\n",
    "#   discounted: map\n",
    "#   a_names: filter\n",
    "#   long_upper: both\n",
    "prices = [4.5, 12.0, 7.25, 20.0, 3.0]\n",
    "names = ['apple', 'avocado', 'banana', 'apricot', 'cherry']\n",
    "\n",
    "discounted = list(map(lambda p: round(p * 0.9, 2), prices))\n",
    "a_names = list(filter(lambda n: n.startswith('a'), names))\n",
    "long_upper = list(map(lambda n: n.upper(), filter(lambda n: len(n) > 5, names)))\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-comp-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "discounted: map\n",
      "a_names: filter\n",
      "long_upper: both\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "prices = [4.5, 12.0, 7.25, 20.0, 3.0]\n",
    "names = ['apple', 'avocado', 'banana', 'apricot', 'cherry']\n",
    "\n",
    "discounted = list(map(lambda p: round(p * 0.9, 2), prices))\n",
    "a_names = list(filter(lambda n: n.startswith('a'), names))\n",
    "long_upper = list(map(lambda n: n.upper(), filter(lambda n: len(n) > 5, names)))\n",
    "\n",
    "discounted_c = [round(p * 0.9, 2) for p in prices]                  # map: transforms every item\n",
    "a_names_c = [n for n in names if n.startswith('a')]                 # filter: keeps some items unchanged\n",
    "long_upper_c = [n.upper() for n in names if len(n) > 5]             # both: keeps some, transforms them\n",
    "\n",
    "print(discounted_c == discounted)       # True\n",
    "print(a_names_c == a_names)             # True\n",
    "print(long_upper_c == long_upper)       # True\n",
    "print(\"discounted: map\")\n",
    "print(\"a_names: filter\")\n",
    "print(\"long_upper: both\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11f5de95",
   "metadata": {},
   "source": [
    "## Choosing a Style\n",
    "\n",
    "```{index} list comprehension, map()\n",
    "```\n",
    "\n",
    "Both `comprehension` and `map`/`filter` approaches transform or filter sequences, but they communicate intent differently.\n",
    "\n",
    "| Situation | Prefer |\n",
    "|---|---|\n",
    "| Simple transformation (`x * 2`, `s.upper()`) | Comprehension: reads like English |\n",
    "| Named function already defined (`str.upper`, `int`) | `map(fn, seq)`: no need to rewrap it in a lambda |\n",
    "| Transforming *and* filtering in one pass | Comprehension: `[f(x) for x in seq if cond(x)]` is cleaner |\n",
    "| Chaining several transformations | Comprehension, or named intermediate steps: nested `map(filter(...))` reads inside out |\n",
    "| Result must be lazy / memory-sensitive | `map`/`filter`: they return iterators, not lists |\n",
    "\n",
    "**Readability rule of thumb**: if you have to stop and re-read the lambda inside `map` or `filter` to follow it, replace it with a named function or a comprehension. About 30 characters, roughly a single comparison, is where most readers start to slow down.\n",
    "\n",
    "```python\n",
    "# Hard to read — lambda is too complex\n",
    "result = list(filter(lambda s: len(s) > 3 and s.startswith('a'), words))\n",
    "\n",
    "# Clearer as a comprehension\n",
    "result = [s for s in words if len(s) > 3 and s.startswith('a')]\n",
    "```\n",
    "\n",
    "**Pipeline readability check**: a functional pipeline of 2–3 steps is fine. For longer chains, break steps into named intermediate variables so the intent stays obvious.\n",
    "\n",
    "**Lazy versus eager.** `map()` and `filter()` return iterators: nothing is computed until you consume them, and they can be consumed only once. A list comprehension builds the whole list immediately. The next cell shows the difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-lazy-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "\n",
    "squares = map(lambda x: x ** 2, numbers)\n",
    "print(squares)              # <map object at 0x...>: nothing has been computed yet\n",
    "print(list(squares))        # [1, 4, 9, 16]: consuming the iterator computes the values\n",
    "print(list(squares))        # []: the iterator is already exhausted\n",
    "\n",
    "squares_list = [x ** 2 for x in numbers]\n",
    "print(squares_list)         # [1, 4, 9, 16]\n",
    "print(squares_list)         # [1, 4, 9, 16]: a list can be read again"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "style-practice",
   "metadata": {},
   "source": [
    "**Practice.** Choose a style for each task, and say why, before you open the feedback:\n",
    "\n",
    "1. Convert the strings in `['1', '2', '3']` to integers.\n",
    "2. Keep the names longer than three letters and make them uppercase.\n",
    "3. Add up the squares of the numbers from 1 to 1,000,000 without storing them all.\n",
    "\n",
    "```{admonition} Check your reasoning\n",
    ":class: dropdown\n",
    "1. `map(int, items)`: a named function already exists, so no lambda or comprehension body is needed.\n",
    "2. A comprehension, `[n.upper() for n in names if len(n) > 3]`: it transforms and filters in one readable pass.\n",
    "3. A lazy pipeline, `sum(map(lambda x: x ** 2, range(1, 1_000_001)))`: `map()` produces one square at a time and `sum()` consumes them, so no million-item list is built. A comprehension in brackets would build the whole list first.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "32e4389e",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Sorting and Filtering with Lambda\n",
    "#   Given the student records below (name, grade, year):\n",
    "#   1. Use filter() with a lambda to keep students with grade >= 80.\n",
    "#   2. Use sorted() with a lambda to rank passing students by grade, highest first.\n",
    "#   3. Use map() with a lambda to extract just the names.\n",
    "#   4. Print the final list of names.\n",
    "#      Expected output: ['Charlie', 'Eve', 'Alice']\n",
    "students = [\n",
    "    ('Alice', 85, 'junior'), ('Bob', 72, 'senior'),\n",
    "    ('Charlie', 91, 'sophomore'), ('Diana', 65, 'junior'), ('Eve', 88, 'senior')\n",
    "]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "40a86c47",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Charlie', 'Eve', 'Alice']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "students = [\n",
    "    ('Alice', 85, 'junior'), ('Bob', 72, 'senior'),\n",
    "    ('Charlie', 91, 'sophomore'), ('Diana', 65, 'junior'), ('Eve', 88, 'senior')\n",
    "]\n",
    "passing = list(filter(lambda s: s[1] >= 80, students))\n",
    "ranked  = sorted(passing, key=lambda s: s[1], reverse=True)\n",
    "names   = list(map(lambda s: s[0], ranked))\n",
    "print(names)  # ['Charlie', 'Eve', 'Alice']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-pipeline-design-md",
   "metadata": {},
   "source": [
    "## Designing a Pipeline\n",
    "\n",
    "A pipeline passes the result of one transformation to the next. To design one, first identify what each stage receives and what it must produce. Give a stage a name when its output has a useful meaning that you can inspect or test separately.\n",
    "\n",
    "Suppose an inventory extract contains strings in the form `fruit:quantity`. A quantity is either blank or a nonnegative integer written as text. Every record has a colon and a nonempty fruit name. The task is to keep fruits with at least three items and rank them by quantity, highest first. Malformed records are outside this example's input contract; a real import would validate them or handle conversion errors explicitly.\n",
    "\n",
    "The following loop mixes text cleanup, conversion, selection, and ranking. It is a working baseline for checking the pipeline:\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-pipeline-baseline-code",
   "metadata": {},
   "source": [
    "raw_inventory = [' apple : 3 ', 'banana:', 'pear:0', 'orange:5']\n",
    "original_inventory = raw_inventory.copy()\n",
    "\n",
    "inventory_loop = []\n",
    "for line in raw_inventory:\n",
    "    fruit, _, quantity_text = line.partition(':')\n",
    "    fruit = fruit.strip().title()\n",
    "    quantity_text = quantity_text.strip()\n",
    "    if quantity_text == '':\n",
    "        continue\n",
    "    quantity = int(quantity_text)\n",
    "    if quantity >= 3:\n",
    "        inventory_loop.append((fruit, quantity))\n",
    "inventory_loop.sort(key=lambda item: item[1], reverse=True)\n",
    "print(inventory_loop)\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Orange', 5), ('Apple', 3)]\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-pipeline-stages-md",
   "metadata": {},
   "source": [
    "Choose boundaries where the meaning or representation of a record changes:\n",
    "\n",
    "| Stage | Input record | Output record | Reason for this boundary |\n",
    "|---|---|---|---|\n",
    "| Parse and normalize | `' apple : 3 '` | `('Apple', '3')` | Later stages should not repeat text cleanup. |\n",
    "| Remove missing quantities and convert | `('Apple', '3')` | `('Apple', 3)` | Numeric operations need integers; blank quantities must be removed before conversion. |\n",
    "| Select sufficient stock | `('Apple', 3)` | The same tuple, if its quantity is at least three | Selection changes which records remain, not their shape. |\n",
    "| Rank | A list of selected tuples | The same records in descending quantity order | Ranking depends on the selected collection as a whole. |\n",
    "\n",
    "The first stage uses a pure helper because field cleanup takes several operations. `line.partition(':')` returns the text before the first colon, the separator itself, and the text after it. The name `_` receives the separator, which this helper does not use. Strip each field separately: stripping the whole line would leave the space before the colon in `' apple : 3 '`.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-pipeline-helper-code",
   "metadata": {},
   "source": [
    "def parse_inventory(line):\n",
    "    fruit, _, quantity_text = line.partition(':')\n",
    "    return fruit.strip().title(), quantity_text.strip()\n",
    "\n",
    "print(parse_inventory(' apple : 3 '))\n",
    "print(parse_inventory('banana:'))\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Apple', '3')\n",
      "('Banana', '')\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-pipeline-build-md",
   "metadata": {},
   "source": [
    "Build the remaining stages from the helper's return value. In `converted`, the comprehension's `if` clause checks the text before the expression calls `int()`. This order prevents `int('')` from raising `ValueError`. Once conversion is complete, every quantity is an integer, so the next stage can compare it with `3`.\n",
    "\n",
    "Print the intermediate collections to check the design. A missing fruit in `parsed` points to parsing; a wrong numeric value in `converted` points to conversion. Named boundaries make that distinction visible without reading one deeply nested expression.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch10-pipeline-build-code",
   "metadata": {},
   "source": [
    "parsed_inventory = [parse_inventory(line) for line in raw_inventory]\n",
    "converted_inventory = [(fruit, int(text)) for fruit, text in parsed_inventory if text != '']\n",
    "stocked_inventory = [item for item in converted_inventory if item[1] >= 3]\n",
    "ranked_inventory = sorted(stocked_inventory, key=lambda item: item[1], reverse=True)\n",
    "\n",
    "print('Parsed:', parsed_inventory)\n",
    "print('Converted:', converted_inventory)\n",
    "print('Selected:', stocked_inventory)\n",
    "print('Ranked:', ranked_inventory)\n",
    "print('Same result:', ranked_inventory == inventory_loop)\n",
    "print('Input unchanged:', raw_inventory == original_inventory)\n"
   ],
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parsed: [('Apple', '3'), ('Banana', ''), ('Pear', '0'), ('Orange', '5')]\n",
      "Converted: [('Apple', 3), ('Pear', 0), ('Orange', 5)]\n",
      "Selected: [('Apple', 3), ('Orange', 5)]\n",
      "Ranked: [('Orange', 5), ('Apple', 3)]\n",
      "Same result: True\n",
      "Input unchanged: True\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch10-pipeline-interpret-md",
   "metadata": {},
   "source": [
    "The blank quantity survives parsing as `('Banana', '')` but is removed before conversion. Pear becomes `('Pear', 0)` and is removed by the stock rule. Apple and Orange remain, and ranking puts Orange first. The two final `True` values check different properties: agreement with the baseline on this dataset and preservation of the original input. Agreement on one dataset does not establish correctness for every allowed input.\n",
    "\n",
    "Each helper call returns a new tuple, each comprehension builds a new list, and `sorted()` returns a new list. These stages leave their inputs unchanged. The named lists also use memory; keeping every intermediate list is useful for this small worked example, but a large stream may need lazy stages (developed in Chapter 11). A pipeline is worthwhile when these boundaries make the transformations easier to understand.\n",
    "\n",
    "**Practice.** Answer both questions before reading the feedback:\n",
    "\n",
    "1. Predict what changes if the stock threshold becomes six.\n",
    "2. Explain why checking `text >= 3` in the conversion stage would fail.\n",
    "\n",
    "```{admonition} Check your reasoning\n",
    ":class: dropdown\n",
    "1. With a threshold of six, `stocked_inventory` and `ranked_inventory` are empty; parsing and conversion are unchanged. The baseline's threshold must also change before comparing the results.\n",
    "2. In the conversion stage, `text` is still a string, so `text >= 3` compares a string with an integer and raises `TypeError`. Filter missing text first, convert it, and then apply the numeric stock rule.\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-pipeline-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Refactor a Loop into a Pipeline\n",
    "#   Each row below is `name | score | department`. The loop keeps the rows with a score from\n",
    "#   0 to 100 and records the best row in each department. A blank score or a score outside\n",
    "#   0-100 is invalid. Rewrite the loop as a pipeline of small pure steps:\n",
    "#   1. Write `parse_row(line)` that returns (name, score_text, dept): split on '|', strip each\n",
    "#      field, capitalize the name with title(), and upper-case the department.\n",
    "#   2. Build `valid` with comprehensions: convert score_text to an int for rows with a score,\n",
    "#      then keep rows whose score is from 0 to 100.\n",
    "#   3. Build `best_pipeline` as a dictionary comprehension that maps each department in `valid`\n",
    "#      to the (name, score) pair with the highest score. Hint: max(..., key=...).\n",
    "#   4. Check that best_pipeline == best_loop and that raw_rows is unchanged.\n",
    "raw_rows = ['  alice | 85 | cs', 'BOB | | cs', 'carol | 140 | math', 'dan | 72 | math', ' eve | 91 | cs ']\n",
    "\n",
    "best_loop = {}\n",
    "for line in raw_rows:\n",
    "    name, score, dept = [part.strip() for part in line.split('|')]\n",
    "    if score == '':\n",
    "        continue\n",
    "    score = int(score)\n",
    "    if not 0 <= score <= 100:\n",
    "        continue\n",
    "    dept = dept.upper()\n",
    "    if dept not in best_loop or score > best_loop[dept][1]:\n",
    "        best_loop[dept] = (name.title(), score)\n",
    "print(best_loop)        # {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch10-pipeline-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "raw_rows = ['  alice | 85 | cs', 'BOB | | cs', 'carol | 140 | math', 'dan | 72 | math', ' eve | 91 | cs ']\n",
    "\n",
    "best_loop = {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}\n",
    "\n",
    "def parse_row(line):\n",
    "    name, score_text, dept = [part.strip() for part in line.split('|')]\n",
    "    return name.title(), score_text, dept.upper()\n",
    "\n",
    "parsed = [parse_row(line) for line in raw_rows]\n",
    "converted = [(name, int(text), dept) for name, text, dept in parsed if text != '']\n",
    "valid = [row for row in converted if 0 <= row[1] <= 100]\n",
    "best_pipeline = {\n",
    "    dept: max(((name, score) for name, score, d in valid if d == dept), key=lambda pair: pair[1])\n",
    "    for dept in sorted({row[2] for row in valid})\n",
    "}\n",
    "\n",
    "print(best_pipeline)                    # {'CS': ('Eve', 91), 'MATH': ('Dan', 72)}\n",
    "print(best_pipeline == best_loop)       # True\n",
    "print(raw_rows)                         # unchanged\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pandas-bridge-md",
   "metadata": {},
   "source": [
    "## Bridge: From Pipelines to pandas\n",
    "\n",
    "*Optional preview.* Data science libraries use the same ideas you have practiced in this chapter. In pandas, a table is a `DataFrame` and a column is a `Series`. The names differ, but the tools line up with this chapter: element-wise transformation, row-wise functions, filtering, sorting, and pipelines that return new values.\n",
    "\n",
    "| Plain Python | pandas |\n",
    "|---|---|\n",
    "| `map(f, items)` | `series.map(f)` applies `f` to every value in a column |\n",
    "| Calling a function on a whole record | `df.apply(f, axis=1)` passes each row to `f` |\n",
    "| `filter()` or an `if` clause | `df.query('curved >= 80')` keeps matching rows |\n",
    "| `sorted(items, key=...)` | `df.sort_values('curved')` |\n",
    "| Chained steps with named intermediate lists | A **method chain**: each step returns a new `DataFrame` |\n",
    "\n",
    "The cell below reuses the `make_curve` closure from the Closures section as the function passed to `.map()`."
   ]
  },
  {
   "cell_type": "code",
   "id": "pandas-bridge-code1",
   "metadata": {},
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    'name': ['alice', 'bob', 'carol', 'dan'],\n",
    "    'score': [85, 72, 91, 65],\n",
    "    'section': ['A', 'B', 'A', 'B'],\n",
    "})\n",
    "\n",
    "# Series.map: like map(), one value at a time\n",
    "print(df['name'].map(str.title).tolist())                # ['Alice', 'Bob', 'Carol', 'Dan']\n",
    "print(df['score'].map(make_curve(5)).tolist())           # [90, 77, 96, 70]: the closure from earlier\n",
    "\n",
    "# DataFrame.apply with axis=1: the function receives a whole row\n",
    "labels = df.apply(lambda row: f\"{row['name'].title()} ({row['section']})\", axis=1)\n",
    "print(labels.tolist())                                   # ['Alice (A)', 'Bob (B)', 'Carol (A)', 'Dan (B)']"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "pandas-bridge-md2",
   "metadata": {},
   "source": [
    "A method chain reads like the pipeline you designed earlier: each step takes the previous result and returns a new `DataFrame`, so the original is not changed. `assign()` adds or replaces columns (with a lambda that receives the current table), `query()` selects rows, and `sort_values()` ranks them."
   ]
  },
  {
   "cell_type": "code",
   "id": "pandas-bridge-code2",
   "metadata": {},
   "source": [
    "top = (\n",
    "    df.assign(name=lambda d: d['name'].map(str.title),\n",
    "              curved=lambda d: d['score'].map(make_curve(5)))\n",
    "      .query('curved >= 80')\n",
    "      .sort_values('curved', ascending=False)\n",
    "      [['name', 'curved']]\n",
    ")\n",
    "print(top)\n",
    "#     name  curved\n",
    "# 2  Carol      96\n",
    "# 0  Alice      90\n",
    "\n",
    "print(df['name'].tolist())      # ['alice', 'bob', 'carol', 'dan']: the original table is unchanged"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "pandas-bridge-md3",
   "metadata": {},
   "source": [
    "Two cautions. `.map()` and `.apply()` call a Python function once per value or row, which is slow on large tables. When pandas offers a column operation, such as `df['score'] + 5`, use it instead. Use `.map()` and `.apply()` when the logic is a custom function you cannot express with column operations. Also, `.apply(axis=1)` passes a row to your function, so the function is pure as long as it only reads that row."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3c14435",
   "metadata": {},
   "source": [
    "## Footnotes\n",
    "\n",
    "[^paradigms]: The diagram is adapted from Pradeesh Kumar, \"Programming Paradigms,\" *Medium*. Paradigm boundaries are not strict: many languages, including Python, support more than one.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.13.7)",
   "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
}
