{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# ADT Basics\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {},
   "source": [
    "This section introduces the central design idea of the chapter: separate what a collection does from how it is implemented.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interface",
   "metadata": {},
   "source": [
    "## Abstract Types and Implementations\n",
    "\n",
    "An **abstract data type** defines behavior. It says what operations are supported and what each operation means. A **concrete implementation** says how values are stored and how each operation is performed.\n",
    "\n",
    "| Abstract idea | Required behavior | Possible Python implementation |\n",
    "| --- | --- | --- |\n",
    "| Stack | Add and remove from the same end | `list` |\n",
    "| Queue | Add at the back, remove from the front | `collections.deque` |\n",
    "| Set | Store unique values and test membership | `set` |\n",
    "| Map | Associate keys with values | `dict` |\n",
    "| Graph | Store nodes and relationships | `dict[str, list[str]]` |\n",
    "\n",
    "The important design question is not which container looks familiar. The important question is which operations the problem needs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-interface",
   "metadata": {},
   "source": [
    "```{index} abstract data type, concrete implementation, deque\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "membership-intro",
   "metadata": {},
   "source": [
    "A `list` and a `set` can answer the same question, \"is `bob` in the collection?\", so for that question they share one behavior. They differ in how they store the names: the list checks them one by one, while the set uses hashing, as Chapter 7 showed. The next cell asks the question both ways and gets the same answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "membership-demo",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nTrue\n"
    }
   ],
   "source": [
    "names_list = [\"alice\", \"bob\", \"charlie\"]\n",
    "names_set = {\"alice\", \"bob\", \"charlie\"}\n",
    "\n",
    "print(\"bob\" in names_list)\n",
    "print(\"bob\" in names_set)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "impl-demo-text",
   "metadata": {},
   "source": [
    "The next example implements one behavior, a stack, in two ways. The second version uses `collections.deque` (short for double-ended queue), a list-like container from the standard library that you import with `from collections import deque`. A deque supports `append()` to add an item at the right end and `pop()` to remove the item at the right end, just like a list. {doc}`13.2 Stacks & Queues <1302-stacks-queues>` uses a deque to build a queue and explains why it beats a list for that job."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "impl-demo",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "list  pop: third\ndeque pop: third\n"
    }
   ],
   "source": [
    "from collections import deque\n",
    "\n",
    "# Two implementations of the same LIFO (last-in, first-out) behavior\n",
    "\n",
    "# list-backed\n",
    "stack_list = []\n",
    "stack_list.append(\"first\")\n",
    "stack_list.append(\"second\")\n",
    "stack_list.append(\"third\")\n",
    "print(\"list  pop:\", stack_list.pop())    # third\n",
    "\n",
    "# deque-backed\n",
    "stack_deque = deque()\n",
    "stack_deque.append(\"first\")\n",
    "stack_deque.append(\"second\")\n",
    "stack_deque.append(\"third\")\n",
    "print(\"deque pop:\", stack_deque.pop())   # third\n",
    "\n",
    "# The caller sees identical behavior.\n",
    "# The choice of implementation affects performance, not correctness.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-interface",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: One Behavior, Two Implementations\n",
    "# A task manager needs to support undo. The last task added is the first one undone.\n",
    "# Implement this LIFO behavior twice: once using a list, once using a deque.\n",
    "#\n",
    "# For each: push \"draft report\", then \"send email\", then \"schedule meeting\".\n",
    "# Pop and print the most recent task from each.\n",
    "# Print exactly:\n",
    "# list undo: schedule meeting\n",
    "# deque undo: schedule meeting\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-interface",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "list undo: schedule meeting\ndeque undo: schedule meeting\n"
    }
   ],
   "source": [
    "### Solution\n",
    "from collections import deque\n",
    "\n",
    "tasks_list = []\n",
    "tasks_list.append(\"draft report\")\n",
    "tasks_list.append(\"send email\")\n",
    "tasks_list.append(\"schedule meeting\")\n",
    "print(\"list undo:\", tasks_list.pop())\n",
    "\n",
    "tasks_deque = deque()\n",
    "tasks_deque.append(\"draft report\")\n",
    "tasks_deque.append(\"send email\")\n",
    "tasks_deque.append(\"schedule meeting\")\n",
    "print(\"deque undo:\", tasks_deque.pop())\n",
    "\n",
    "# Both produce the same result. The behavior (LIFO) is the abstract type.\n",
    "# The container (list or deque) is the implementation.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tradeoffs",
   "metadata": {},
   "source": [
    "## Operation Tradeoffs\n",
    "\n",
    "A data structure is a tradeoff. One structure may make lookup easy but insertion expensive. Another may make insertion easy but searching slower.\n",
    "\n",
    "The four operations to reason about are **access**, **search**, **insert**, and **delete**.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-tradeoffs",
   "metadata": {},
   "source": [
    "```{index} Big O notation, time complexity, logarithmic time (O(log n))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "big-o",
   "metadata": {},
   "source": [
    ":::{note} Operation Costs and Big O\n",
    "\n",
    "You have seen **O(1)** and **O(n)** in Chapter 7, where dictionary and set lookups were compared with list searches. Here is a recap, plus **O(log n)**, which appears with trees.\n",
    "\n",
    "| Notation | Name | Meaning | ADT example |\n",
    "| --- | --- | --- | --- |\n",
    "| O(1) | Constant time | Same speed regardless of size | `dict` key lookup, `set` membership |\n",
    "| O(n) | Linear time | Scales with collection size | `list` search, linear scan |\n",
    "| O(log n) | Logarithmic time | Halves the search space each step | Balanced binary search tree lookup |\n",
    "\n",
    "A binary search tree lookup starts at the root, goes left if the target is smaller and right if larger, and repeats until it finds the value or runs out of nodes. Each step moves down one level, so the cost is **O(h)**, where *h* is the height of the tree.\n",
    "\n",
    "- In a **balanced** tree, each step eliminates about half of the remaining nodes, so h ≈ log₂ n and lookup is O(log n). Chapter 14 applies the same halving idea to binary search on a sorted list.\n",
    "- In an **unbalanced** tree, such as one built by inserting values that are already sorted, every node has at most one child. The tree degenerates into a chain with h = n, and lookup becomes O(n).\n",
    "\n",
    "Some costs are **amortized**: averaged over many operations. `list.append()` occasionally copies the whole list to make room, but spread over many appends, each one costs O(1).\n",
    "\n",
    "Self-balancing trees (such as AVL and red-black trees) restructure themselves on each insert to keep the height close to log n.\n",
    "\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tradeoff-tables",
   "metadata": {},
   "source": [
    "With that notation, here is how the common Python containers compare:\n",
    "\n",
    "| Operation | `list` | `set` | `dict` | `deque` |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Access by index | O(1) | — | — | O(1) at ends, O(n) in middle |\n",
    "| Look up by key | — | — | O(1) avg | — |\n",
    "| Search for value | O(n) | O(1) avg | O(n) | O(n) |\n",
    "| Insert / add | O(1) amortized (back) | O(1) avg | O(1) avg | O(1) (either end) |\n",
    "| Insert at front | O(n) | — | — | O(1) |\n",
    "| Delete by key | — | — | O(1) avg | — |\n",
    "| Delete by value | O(n) | O(1) avg | O(n) | O(n) |\n",
    "\n",
    "A `dict` is fast only when you work through its **keys**. Finding which key holds a given value means scanning every entry, which is O(n), just like a `list`. A `set` stores only keys, so membership tests are O(1) on average.\n",
    "\n",
    "Use this table to match the dominant operation in your workload to the right structure:\n",
    "\n",
    "| Dominant need | Best choice | Why |\n",
    "| --- | --- | --- |\n",
    "| Ordered history, access by position | `list` | O(1) index access |\n",
    "| Fast membership or deduplication | `set` | O(1) avg search |\n",
    "| Key-value lookup | `dict` | O(1) avg lookup |\n",
    "| Add or remove from both ends | `deque` | O(1) at front and back |\n",
    "| Hierarchical containment | tree | Parent-child links mirror the hierarchy; a balanced binary search tree adds O(log n) search |\n",
    "| Many-to-many relationships | graph | Depends on traversal |\n",
    "\n",
    "Before coding, write down the operations your program will perform most often.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tradeoff-demo",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "list  (O(n)):     0.000605 s   — scans up to 100,000 items\nset   (O(1) avg): 0.000020 s   — jumps via hash\n"
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "n = 100_000\n",
    "data_list = list(range(n))\n",
    "data_set = set(data_list)\n",
    "target = n - 1  # worst case for list: last element\n",
    "\n",
    "start = time.perf_counter()\n",
    "_ = target in data_list\n",
    "list_time = time.perf_counter() - start\n",
    "\n",
    "start = time.perf_counter()\n",
    "_ = target in data_set\n",
    "set_time = time.perf_counter() - start\n",
    "\n",
    "print(f\"list  (O(n)):     {list_time:.6f} s   — scans up to {n:,} items\")\n",
    "print(f\"set   (O(1) avg): {set_time:.6f} s   — jumps via hash\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-tradeoffs",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Match Workload to Structure\n",
    "# For each workload description, write the best Python structure.\n",
    "# Choose from: list, set, dict, deque.\n",
    "#\n",
    "# 1. Store chat messages in the order sent; retrieve by position.\n",
    "# 2. Track which email addresses have already received a newsletter.\n",
    "# 3. Map each student name to their grade.\n",
    "# 4. Process print jobs: add new jobs at the back, serve from the front.\n",
    "# Fill in each value in the `workload` dict, then print it.\n",
    "# Print exactly:\n",
    "# {'ordered messages, access by position': 'list', 'track seen email addresses': 'set', 'name to grade mapping': 'dict', 'job queue: add at back, remove from front': 'deque'}\n",
    "### Your code starts here.\n",
    "\n",
    "workload = {\n",
    "    \"ordered messages, access by position\": \"\",\n",
    "    \"track seen email addresses\": \"\",\n",
    "    \"name to grade mapping\": \"\",\n",
    "    \"job queue: add at back, remove from front\": \"\",\n",
    "}\n",
    "\n",
    "print(workload)\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-tradeoffs",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "{'ordered messages, access by position': 'list', 'track seen email addresses': 'set', 'name to grade mapping': 'dict', 'job queue: add at back, remove from front': 'deque'}\n"
    }
   ],
   "source": [
    "### Solution\n",
    "workload = {\n",
    "    \"ordered messages, access by position\": \"list\",\n",
    "    \"track seen email addresses\": \"set\",\n",
    "    \"name to grade mapping\": \"dict\",\n",
    "    \"job queue: add at back, remove from front\": \"deque\",\n",
    "}\n",
    "print(workload)\n",
    "\n",
    "# list:  O(1) append and O(1) index access.\n",
    "# set:   O(1) avg membership check — ideal for deduplication.\n",
    "# dict:  O(1) avg key lookup.\n",
    "# deque: O(1) at both ends — list.insert(0, x) is O(n).\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
