{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f505610a",
   "metadata": {},
   "source": [
    "# Pipelines and itertools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d909faf9",
   "metadata": {},
   "source": [
    "Generators become most useful when you chain them. This section builds lazy pipelines from the generator functions and expressions in {doc}`1102-generators`, explains what happens when an iterator runs out, produces infinite sequences, delegates with `yield from`, and surveys more of `itertools`. It ends with a bridge to async iteration and a guide to choosing among the tools in this chapter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a4c4da6",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-h",
   "metadata": {},
   "source": [
    "## Generator Pipelines"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ch11-pipe",
   "metadata": {},
   "source": [
    "```{index} generator pipeline, consumer (pipeline), iterator exhaustion\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-intro",
   "metadata": {},
   "source": [
    "A **generator pipeline** is a chain of small generators in which each stage consumes the output of the stage before it. Every stage does one job: one produces raw records, the next parses them, the next filters them, and a final **consumer** such as `sum()`, `list()`, `max()`, or a `for` loop reduces the stream to a result.\n",
    "\n",
    "The stages are lazy. Building the chain only creates generator objects; no record is read, parsed, or filtered until the consumer asks for its first value. Each request then travels back up the chain, and one value flows down the chain, through every stage or until a filter drops it, before the next value is produced.\n",
    "\n",
    "```text\n",
    "read_rows  ->  parse  ->  in_region  ->  (amount for ...)  ->  sum()\n",
    " raw lines     dicts      East only      numbers               total\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-build",
   "metadata": {},
   "source": [
    "### Building a Pipeline\n",
    "\n",
    "The pipeline below totals the East region's sales from a small block of CSV-style text. The text is an inline string, so you can run the example without any files. Each stage is a generator function that takes an iterable and yields new values, and the last stage is a generator expression that picks out the `amount` field."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-code1",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "<class 'generator'>\n425\n"
    }
   ],
   "source": [
    "SALES = \"\"\"region,product,amount\n",
    "East,apple,120\n",
    "West,banana,85\n",
    "East,cherry,210\n",
    "West,apple,40\n",
    "East,banana,95\"\"\"\n",
    "\n",
    "def read_rows(text):\n",
    "    \"\"\"Stage 1: yield one raw line at a time, skipping the header.\"\"\"\n",
    "    lines = iter(text.splitlines())\n",
    "    next(lines)                      # skip the header row\n",
    "    for line in lines:\n",
    "        yield line\n",
    "\n",
    "def parse(rows):\n",
    "    \"\"\"Stage 2: turn each line into a dict with a numeric amount.\"\"\"\n",
    "    for row in rows:\n",
    "        region, product, amount = row.split(\",\")\n",
    "        yield {\"region\": region, \"product\": product, \"amount\": int(amount)}\n",
    "\n",
    "def in_region(records, region):\n",
    "    \"\"\"Stage 3: keep only the records from one region.\"\"\"\n",
    "    for rec in records:\n",
    "        if rec[\"region\"] == region:\n",
    "            yield rec\n",
    "\n",
    "rows = read_rows(SALES)\n",
    "records = parse(rows)\n",
    "east = in_region(records, \"East\")\n",
    "amounts = (rec[\"amount\"] for rec in east)   # Stage 4: pick one field\n",
    "\n",
    "print(type(amounts))   # <class 'generator'>  (nothing has run yet)\n",
    "print(sum(amounts))    # 425  (sum() pulls every value through the chain)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-trace-md",
   "metadata": {},
   "source": [
    "### Tracing the Flow\n",
    "\n",
    "To see the order in which values move, insert a pass-through stage that prints each item and yields it unchanged. Because `trace()` is itself a generator, you can drop it between any two stages without changing the result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-code2",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": " read: East,apple,120\nparse: {'region': 'East', 'product': 'apple', 'amount': 120}\n keep: {'region': 'East', 'product': 'apple', 'amount': 120}\n read: West,banana,85\nparse: {'region': 'West', 'product': 'banana', 'amount': 85}\n read: East,cherry,210\nparse: {'region': 'East', 'product': 'cherry', 'amount': 210}\n keep: {'region': 'East', 'product': 'cherry', 'amount': 210}\n read: West,apple,40\nparse: {'region': 'West', 'product': 'apple', 'amount': 40}\n read: East,banana,95\nparse: {'region': 'East', 'product': 'banana', 'amount': 95}\n keep: {'region': 'East', 'product': 'banana', 'amount': 95}\ntotal: 425\n"
    }
   ],
   "source": [
    "def trace(label, items):\n",
    "    \"\"\"Pass items through unchanged, printing each one.\"\"\"\n",
    "    for item in items:\n",
    "        print(f\"{label:>5}: {item}\")\n",
    "        yield item\n",
    "\n",
    "rows = trace(\"read\", read_rows(SALES))\n",
    "records = trace(\"parse\", parse(rows))\n",
    "east = trace(\"keep\", in_region(records, \"East\"))\n",
    "\n",
    "total = sum(rec[\"amount\"] for rec in east)\n",
    "print(\"total:\", total)   # total: 425"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-trace-explain",
   "metadata": {},
   "source": [
    "Read the trace from top to bottom. The first line is read, parsed, and kept before the second line is even read. The West records stop at the filter, so `sum()` never sees them. At any moment only one record is in flight, which is why the pipeline scales: if the first stage reads from a file (`for line in f:`) instead of an in-memory string, memory use depends on the size of one record, not the number of records."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-exhaust",
   "metadata": {},
   "source": [
    "### Iterator Exhaustion\n",
    "\n",
    "A generator remembers its position, and it cannot rewind. Once it has raised `StopIteration`, it is **exhausted**: every later request ends immediately. This is called **iterator exhaustion**. It matters in pipelines because a second pass over the same generator silently produces nothing. `sum()` of an empty stream returns `0` and `list()` returns `[]`, so no error warns you. `max()` and `min()` are the exception: they raise `ValueError` on an empty stream, which is often the first sign that a generator was already used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-code3",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "425\n0\n[]\nValueError: max() iterable argument is empty\n"
    }
   ],
   "source": [
    "east = in_region(parse(read_rows(SALES)), \"East\")\n",
    "amounts = (rec[\"amount\"] for rec in east)\n",
    "\n",
    "print(sum(amounts))    # 425\n",
    "print(sum(amounts))    # 0   (the generator is already exhausted)\n",
    "print(list(amounts))   # []\n",
    "\n",
    "try:\n",
    "    max(amounts)\n",
    "except ValueError as e:\n",
    "    print(\"ValueError:\", e)   # max() of an empty stream"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-pipe-fix",
   "metadata": {},
   "source": [
    "There are two fixes, and you choose based on how much data there is:\n",
    "\n",
    "- **Rebuild the pipeline.** Wrap the chain in a function that returns a fresh generator each time you call it. Each call reads the source again, but memory use stays constant.\n",
    "- **Materialize once.** Call `list()` on the pipeline when you need the same values several times and they fit in memory. A list can be iterated as often as you like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-code4",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "425\n210\n[120, 210, 95]\n425 210 3\n"
    }
   ],
   "source": [
    "def east_amounts(text):\n",
    "    \"\"\"Build a fresh pipeline every time it is called.\"\"\"\n",
    "    records = in_region(parse(read_rows(text)), \"East\")\n",
    "    return (rec[\"amount\"] for rec in records)\n",
    "\n",
    "# Fix 1: rebuild the pipeline for each pass\n",
    "print(sum(east_amounts(SALES)))   # 425\n",
    "print(max(east_amounts(SALES)))   # 210\n",
    "\n",
    "# Fix 2: materialize once, then reuse the list\n",
    "amounts = list(east_amounts(SALES))\n",
    "print(amounts)                                    # [120, 210, 95]\n",
    "print(sum(amounts), max(amounts), len(amounts))   # 425 210 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-ex",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Generator Pipeline\n",
    "#   1. Write a generator function `parse_scores(text)` that skips the header\n",
    "#      and yields one (name, score) tuple per line, with score as an int.\n",
    "#   2. Write a function `passing(text, cutoff)` that returns a generator\n",
    "#      expression over parse_scores(text) keeping only scores >= cutoff.\n",
    "#   3. With cutoff 75, print how many scores pass and the highest passing\n",
    "#      score. Build a fresh pipeline for each result.\n",
    "#   Print exactly:\n",
    "#   4 95\n",
    "SCORES = \"\"\"name,quiz,score\n",
    "Alice,1,88\n",
    "Bob,1,72\n",
    "Carol,1,95\n",
    "Alice,2,91\n",
    "Bob,2,58\n",
    "Carol,2,79\"\"\"\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-pipe-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "4 95\n"
    }
   ],
   "source": [
    "### Solution\n",
    "SCORES = \"\"\"name,quiz,score\n",
    "Alice,1,88\n",
    "Bob,1,72\n",
    "Carol,1,95\n",
    "Alice,2,91\n",
    "Bob,2,58\n",
    "Carol,2,79\"\"\"\n",
    "\n",
    "def parse_scores(text):\n",
    "    lines = iter(text.splitlines())\n",
    "    next(lines)                          # skip the header row\n",
    "    for line in lines:\n",
    "        name, quiz, score = line.split(\",\")\n",
    "        yield name, int(score)\n",
    "\n",
    "def passing(text, cutoff):\n",
    "    return ((name, score) for name, score in parse_scores(text) if score >= cutoff)\n",
    "\n",
    "count = sum(1 for _ in passing(SCORES, 75))\n",
    "best = max(score for name, score in passing(SCORES, 75))\n",
    "print(count, best)                 # 4 95"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63336546",
   "metadata": {},
   "source": [
    "## Infinite Sequences\n",
    "\n",
    "Generators also shine when a sequence is too large to build all at once, or has no end at all. The example below represents an endless sequence and takes only as many values as it needs.\n",
    "\n",
    "```{warning}\n",
    "Never pass an infinite generator to `list()`, `sum()`, `max()`, or a `for` loop without a `break`. These consumers keep asking for values that never run out, so the cell runs forever (and with `list()`, memory keeps growing too). Bound it first with `itertools.islice()` or stop at a condition with `next()`. If a cell does hang, use the notebook's interrupt (stop) button.\n",
    "```\n",
    "\n",
    "```{index} infinite generator, itertools.islice()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4151dc45",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import itertools\n",
    "\n",
    "def fibonacci():\n",
    "    \"\"\"Infinite Fibonacci sequence generator.\"\"\"\n",
    "    a, b = 0, 1\n",
    "    while True:\n",
    "        yield a\n",
    "        a, b = b, a + b\n",
    "\n",
    "# Take only the values you need; the rest is never computed\n",
    "fib = fibonacci()\n",
    "first_10 = list(itertools.islice(fib, 10))\n",
    "print(\"First 10 Fibonacci:\", first_10)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n",
    "\n",
    "# Find the first Fibonacci number > 1000\n",
    "fib = fibonacci()\n",
    "big = next(f for f in fib if f > 1000)\n",
    "print(\"First Fibonacci > 1000:\", big)   # 1597"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-gen-pow2-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Powers of Two\n",
    "#   1. Write an infinite generator function `powers_of_two()` that yields\n",
    "#      1, 2, 4, 8, ... forever.\n",
    "#   2. Use itertools.islice to print the first 8 powers as a list.\n",
    "#   3. Use next() with a generator expression over a fresh powers_of_two()\n",
    "#      to print the first power greater than 1000.\n",
    "#   Print exactly:\n",
    "#   [1, 2, 4, 8, 16, 32, 64, 128]\n",
    "#   1024\n",
    "import itertools\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ch11-gen-pow2-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 8, 16, 32, 64, 128]\n",
      "1024\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import itertools\n",
    "\n",
    "def powers_of_two():\n",
    "    value = 1\n",
    "    while True:\n",
    "        yield value\n",
    "        value *= 2\n",
    "\n",
    "print(list(itertools.islice(powers_of_two(), 8)))   # [1, 2, 4, 8, 16, 32, 64, 128]\n",
    "print(next(p for p in powers_of_two() if p > 1000))  # 1024\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e7c6d3b",
   "metadata": {},
   "source": [
    "## `yield from`\n",
    "\n",
    "`yield from` delegates yielding to another iterable (including another generator).\n",
    "For ordinary iteration, it is a shorthand for `for item in sub: yield item`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-4e7c6d3b",
   "metadata": {},
   "source": [
    "```{index} yield from, generator delegation\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbf9a04f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def flatten(nested):\n",
    "    \"\"\"Recursively flatten a nested list structure.\"\"\"\n",
    "    for item in nested:\n",
    "        if isinstance(item, list):\n",
    "            yield from flatten(item)  # delegate to recursive call\n",
    "        else:\n",
    "            yield item\n",
    "\n",
    "data = [1, [2, 3], [4, [5, 6]], 7]\n",
    "print(list(flatten(data)))   # [1, 2, 3, 4, 5, 6, 7]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "266e59ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# yield from with multiple sub-generators\n",
    "def combined(*iterables):\n",
    "    for it in iterables:\n",
    "        yield from it\n",
    "\n",
    "result = list(combined([1, 2], 'ab', range(3)))\n",
    "print(result)   # [1, 2, 'a', 'b', 0, 1, 2]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-gen-yf-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Shelf Inventory with yield from\n",
    "#   1. Write a generator function `inventory(*shelves)` that uses `yield from`\n",
    "#      to produce every item on each shelf in order, then yields \"END\"\n",
    "#      after the last shelf.\n",
    "#   2. Print list(inventory(...)) for the three shelves below.\n",
    "#   Print exactly:\n",
    "#   ['pen', 'ink', 'mug', 'END']\n",
    "front = ['pen', 'ink']\n",
    "back = ['mug']\n",
    "empty = []\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ch11-gen-yf-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['pen', 'ink', 'mug', 'END']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "front = ['pen', 'ink']\n",
    "back = ['mug']\n",
    "empty = []\n",
    "\n",
    "def inventory(*shelves):\n",
    "    for shelf in shelves:\n",
    "        yield from shelf   # an empty shelf yields nothing\n",
    "    yield \"END\"\n",
    "\n",
    "print(list(inventory(front, back, empty)))   # ['pen', 'ink', 'mug', 'END']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64b94d17",
   "metadata": {},
   "source": [
    "## More `itertools`\n",
    "\n",
    "The `itertools` module provides iterator building-blocks. Beyond `islice`, five more are especially useful in data processing.\n",
    "\n",
    "| Function | Description | Example |\n",
    "|---|---|---|\n",
    "| `chain(*iterables)` | Joins iterables end to end, lazily | `chain('AB', 'CD')` → A, B, C, D |\n",
    "| `count(start, step)` | Infinite counter | `count(1, 2)` → 1, 3, 5, … |\n",
    "| `cycle(iterable)` | Repeats iterable endlessly | `cycle('AB')` → A, B, A, B, … |\n",
    "| `combinations(it, r)` | All r-length combos (order doesn't matter) | `combinations('ABC', 2)` → AB AC BC |\n",
    "| `permutations(it, r)` | All ordered r-length arrangements | `permutations('AB', 2)` → AB BA |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-64b94d17",
   "metadata": {},
   "source": [
    "```{index} itertools module, itertools.chain(), itertools.count(), itertools.cycle(), itertools.combinations(), itertools.permutations()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29b5d7c1",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import itertools\n",
    "\n",
    "# count: infinite arithmetic sequence\n",
    "evens = itertools.islice(itertools.count(0, 2), 5)\n",
    "print('First 5 even numbers:', list(evens))  # [0, 2, 4, 6, 8]\n",
    "\n",
    "# cycle: the library version of the Cycle class from Iterators\n",
    "servers = ['A', 'B', 'C']\n",
    "requests = list(itertools.islice(itertools.cycle(servers), 7))\n",
    "print('Request routing:', requests)   # ['A', 'B', 'C', 'A', 'B', 'C', 'A']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-chain-md",
   "metadata": {},
   "source": [
    "`chain()` connects several iterables into one stream. It reads the first iterable to the end and then moves on to the next one, without copying anything into a new list. You can think of it as the library version of the `combined()` generator from the `yield from` section. Because `chain()` is lazy, it works with generators as well as lists: nothing is read from any input until you ask for values.\n",
    "\n",
    "`chain.from_iterable()` does the same job for a single iterable whose items are themselves iterables, such as a list of lists."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ch11-chain-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "chain\n",
      "['apple', 'banana', 'CHERRY', 'DATE']\n",
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "import itertools\n",
    "\n",
    "morning = ['apple', 'banana']                                  # a list\n",
    "afternoon = (fruit.upper() for fruit in ['cherry', 'date'])    # a generator\n",
    "\n",
    "all_fruits = itertools.chain(morning, afternoon)\n",
    "print(type(all_fruits).__name__)   # chain  (nothing has been read yet)\n",
    "print(list(all_fruits))            # ['apple', 'banana', 'CHERRY', 'DATE']\n",
    "\n",
    "# chain.from_iterable: flatten one level of a list of lists\n",
    "baskets = [[1, 2], [3], [4, 5]]\n",
    "print(list(itertools.chain.from_iterable(baskets)))   # [1, 2, 3, 4, 5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe4c6b66",
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools\n",
    "\n",
    "# combinations: choose without caring about order\n",
    "teams = list(itertools.combinations(['Alice', 'Bob', 'Carol'], 2))\n",
    "print('Possible pairs:', teams)\n",
    "# [('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')]\n",
    "\n",
    "# permutations: order matters (e.g. race positions)\n",
    "podium = list(itertools.permutations(['Gold', 'Silver', 'Bronze'], 2))\n",
    "print(f'Top-2 orderings: {len(podium)} total')\n",
    "print(podium[:3])   # first 3 arrangements\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b836bec3",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: itertools\n",
    "#   1. Use itertools.count() and islice() to generate the first 8\n",
    "#      multiples of 7 (7, 14, 21, ..., 56).\n",
    "#   2. Deal cards 1 to 12 to 4 players in turn. Use itertools.cycle() for the\n",
    "#      players 'North', 'East', 'South', 'West', and zip() it with range(1, 13).\n",
    "#      zip() stops at the shorter input, which bounds the infinite cycle.\n",
    "#      Print the list of (player, card) pairs.\n",
    "#   3. Use itertools.combinations() to find all 3-letter combinations\n",
    "#      from 'ABCDE' and print how many there are.\n",
    "#   Print exactly:\n",
    "#   [7, 14, 21, 28, 35, 42, 49, 56]\n",
    "#   [('North', 1), ('East', 2), ('South', 3), ('West', 4), ('North', 5), ('East', 6), ('South', 7), ('West', 8), ('North', 9), ('East', 10), ('South', 11), ('West', 12)]\n",
    "#   10 combinations\n",
    "import itertools\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4648a52",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[7, 14, 21, 28, 35, 42, 49, 56]\n[('North', 1), ('East', 2), ('South', 3), ('West', 4), ('North', 5), ('East', 6), ('South', 7), ('West', 8), ('North', 9), ('East', 10), ('South', 11), ('West', 12)]\n10 combinations\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import itertools\n",
    "\n",
    "# 1. First 8 multiples of 7\n",
    "multiples = list(itertools.islice(itertools.count(7, 7), 8))\n",
    "print(multiples)   # [7, 14, 21, 28, 35, 42, 49, 56]\n",
    "\n",
    "# 2. Deal 3 cards each to 4 players\n",
    "players = itertools.cycle(['North', 'East', 'South', 'West'])\n",
    "cards   = range(1, 13)  # card values 1-12\n",
    "deal    = list(zip(players, cards))   # zip stops when cards runs out\n",
    "print(deal)\n",
    "# [('North', 1), ('East', 2), ('South', 3), ('West', 4),\n",
    "#  ('North', 5), ('East', 6), ...]\n",
    "\n",
    "# 3. Count 3-letter combinations from 'ABCDE'\n",
    "combos = list(itertools.combinations('ABCDE', 3))\n",
    "print(f'{len(combos)} combinations')   # 10\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bcd8836",
   "metadata": {},
   "source": [
    "## Bridge: Async Iteration\n",
    "\n",
    "Synchronous generators pause at `yield` and resume when `next()` is called, all within a single thread. **Async generators** do the same thing, but they can also pause to *wait for I/O* (a network response, a database query, a file read) without blocking other work.\n",
    "\n",
    "The pattern mirrors what you have seen, but uses `async def` with `yield`, and requires `async for` to consume:\n",
    "\n",
    "```python\n",
    "import asyncio\n",
    "\n",
    "async def async_count(n):\n",
    "    \"\"\"Yields 0..n-1, simulating a pause between each.\"\"\"\n",
    "    for i in range(n):\n",
    "        await asyncio.sleep(0)   # hands control back to the event loop\n",
    "        yield i\n",
    "\n",
    "async def main():\n",
    "    async for value in async_count(5):\n",
    "        print(value)\n",
    "\n",
    "asyncio.run(main())   # 0 1 2 3 4  (in a script)\n",
    "```\n",
    "\n",
    "In a Jupyter notebook an event loop is already running, so `asyncio.run()` raises `RuntimeError`. In a notebook cell, write `await main()` instead.\n",
    "\n",
    "**Key vocabulary for future study:**\n",
    "\n",
    "| Term | Meaning |\n",
    "|---|---|\n",
    "| `async def` | Declares a coroutine (or async generator if it uses `yield`) |\n",
    "| `await` | Pauses the coroutine until the awaited task is ready |\n",
    "| `async for` | Iterates over an async iterable, awaiting each item; other tasks can run while it waits |\n",
    "| Event loop | The scheduler that runs coroutines concurrently |\n",
    "\n",
    "You do not need to master `asyncio` now. The takeaway: async iteration mirrors the protocol you learned here. An async iterator implements `__aiter__()` and `__anext__()` instead of `__iter__()` and `__next__()`, signals the end with `StopAsyncIteration`, and an async generator pauses at `yield` the same way a generator does."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-0bcd8836",
   "metadata": {},
   "source": [
    "```{index} async generator, async for\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b97df48",
   "metadata": {},
   "source": [
    "## Choosing a Tool\n",
    "\n",
    "Each tool in this chapter fits a different job. Start with the simplest one that works:\n",
    "\n",
    "| You need | Use | Example |\n",
    "|---|---|---|\n",
    "| Values you will use several times, or need `len()` or indexing | a list | `prices = [12, 5, 8]` |\n",
    "| One pass of a simple transform or filter | a generator expression | `sum(p * 1.1 for p in prices)` |\n",
    "| One pass with several steps, state, or `try`/`except` | a generator function | `running_total(numbers)` |\n",
    "| An object that can be looped over many times | a class whose `__iter__()` is a generator | `CountdownRange(3)` |\n",
    "| An iterator with extra methods or state that other code inspects | a class with `__iter__()` and `__next__()` | `Countdown(5)` (protocol demo) |\n",
    "| A standard pattern: slicing, joining, repeating, combining | `itertools` | `islice`, `chain`, `cycle` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-gen-exercises",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines generator functions, generator expressions, a pipeline, `itertools.islice`, and the fix for iterator exhaustion.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-gen-log-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Error Log Pipeline\n",
    "#   1. Write a generator function `parse_log(text)` that skips the header\n",
    "#      and yields one (time, level, message) tuple per line.\n",
    "#   2. Write a generator function `errors(records)` that yields only the\n",
    "#      records whose level is \"ERROR\".\n",
    "#   3. Write `error_stream(text)` that connects the two stages and returns\n",
    "#      a fresh pipeline each time it is called.\n",
    "#   4. Use itertools.islice to print the times of the first two errors.\n",
    "#   5. Use any() with a generator expression to check whether any error\n",
    "#      message is \"timeout\".\n",
    "#   6. Use sum() with a generator expression to count the errors.\n",
    "#   Build a fresh pipeline for steps 4, 5, and 6.\n",
    "#   Print exactly:\n",
    "#   First two errors: ['09:05', '09:10']\n",
    "#   Any timeout: True\n",
    "#   Error count: 3\n",
    "LOG = \"\"\"time,level,message\n",
    "09:00,INFO,start\n",
    "09:05,ERROR,disk full\n",
    "09:07,INFO,retry\n",
    "09:10,ERROR,timeout\n",
    "09:12,WARN,slow\n",
    "09:15,ERROR,disk full\"\"\"\n",
    "import itertools\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "ch11-gen-log-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First two errors: ['09:05', '09:10']\n",
      "Any timeout: True\n",
      "Error count: 3\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import itertools\n",
    "\n",
    "LOG = \"\"\"time,level,message\n",
    "09:00,INFO,start\n",
    "09:05,ERROR,disk full\n",
    "09:07,INFO,retry\n",
    "09:10,ERROR,timeout\n",
    "09:12,WARN,slow\n",
    "09:15,ERROR,disk full\"\"\"\n",
    "\n",
    "def parse_log(text):\n",
    "    lines = iter(text.splitlines())\n",
    "    next(lines)                          # skip the header row\n",
    "    for line in lines:\n",
    "        time, level, message = line.split(\",\")\n",
    "        yield time, level, message\n",
    "\n",
    "def errors(records):\n",
    "    for time, level, message in records:\n",
    "        if level == \"ERROR\":\n",
    "            yield time, level, message\n",
    "\n",
    "def error_stream(text):\n",
    "    return errors(parse_log(text))\n",
    "\n",
    "first_two = [time for time, _, _ in itertools.islice(error_stream(LOG), 2)]\n",
    "print(\"First two errors:\", first_two)\n",
    "print(\"Any timeout:\", any(msg == \"timeout\" for _, _, msg in error_stream(LOG)))\n",
    "print(\"Error count:\", sum(1 for _ in error_stream(LOG)))\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
