{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# Stacks & Queues\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {},
   "source": [
    "Stacks and queues are linear abstract data types: their items sit in a single sequence, one after another. Both keep items in order, but they remove them in different orders.\n",
    "\n",
    "```text\n",
    "Outline\n",
    "\n",
    "Stacks\n",
    "  o Last-in, first-out behavior\n",
    "  o Python list implementation\n",
    "  o Balanced brackets example\n",
    "Queues\n",
    "  o First-in, first-out behavior\n",
    "  o Why deque, not list\n",
    "  o collections.deque implementation\n",
    "Stack or Queue?\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "stacks",
   "metadata": {},
   "source": [
    "## Stacks\n",
    "\n",
    "A **stack** is a last-in, first-out (**LIFO**) structure: the newest item you add is the first one you remove.\n",
    "\n",
    "Common stack operations:\n",
    "\n",
    "- `push(item)`: add an item to the top\n",
    "- `pop()`: remove and return the top item\n",
    "- `peek()`: look at the top item without removing it\n",
    "- `is_empty()`: check whether the stack has no items\n",
    "\n",
    "Stacks are useful for undo history, browser back buttons, expression evaluation, recursion, and depth-first traversal."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-stacks",
   "metadata": {},
   "source": [
    "```{index} stack, LIFO\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "stack-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "rename variable\nedit line 10\n"
    }
   ],
   "source": [
    "class Stack:\n",
    "    def __init__(self):\n",
    "        self._items = []\n",
    "\n",
    "    def push(self, item):\n",
    "        self._items.append(item)\n",
    "\n",
    "    def pop(self):\n",
    "        if self.is_empty():\n",
    "            raise IndexError(\"pop from empty stack\")\n",
    "        return self._items.pop()\n",
    "\n",
    "    def peek(self):\n",
    "        if self.is_empty():\n",
    "            raise IndexError(\"peek from empty stack\")\n",
    "        return self._items[-1]\n",
    "\n",
    "    def is_empty(self):\n",
    "        return len(self._items) == 0\n",
    "\n",
    "\n",
    "history = Stack()\n",
    "history.push(\"open file\")\n",
    "history.push(\"edit line 10\")\n",
    "history.push(\"rename variable\")\n",
    "\n",
    "print(history.pop())\n",
    "print(history.pop())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "balanced-intro",
   "metadata": {},
   "source": [
    "Stacks are also used to check whether brackets are balanced. Each open bracket is pushed. Each close bracket pops the stack and checks that the popped bracket is its partner. Other characters are skipped. At the end, the stack must be empty: an open bracket still on the stack, as in `\"((a + b)\"`, was never closed.\n",
    "\n",
    "```{index} balanced brackets\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "balanced-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nFalse\nFalse\n"
    }
   ],
   "source": [
    "def is_balanced(expression):\n",
    "    stack = Stack()\n",
    "    pairs = {')': '(', ']': '[', '}': '{'}\n",
    "\n",
    "    for char in expression:\n",
    "        if char in '([{':\n",
    "            stack.push(char)\n",
    "        elif char in ')]}':\n",
    "            if stack.is_empty() or stack.pop() != pairs[char]:\n",
    "                return False\n",
    "\n",
    "    return stack.is_empty()\n",
    "\n",
    "\n",
    "print(is_balanced(\"(a + b) * [c - d]\"))   # True\n",
    "print(is_balanced(\"(a + b] * [c - d]\"))   # False\n",
    "print(is_balanced(\"((a + b)\"))            # False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-stack",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Reverse Words with a Stack\n",
    "# Write a function named reverse_words(sentence) that uses a Stack\n",
    "# to reverse the order of words in a sentence.\n",
    "#\n",
    "# Example: reverse_words(\"data structures matter\") should return\n",
    "# \"matter structures data\".\n",
    "# Call reverse_words(\"data structures matter\") and print the result.\n",
    "# Print exactly:\n",
    "# matter structures data\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-stack",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "matter structures data\n"
    }
   ],
   "source": [
    "### Solution\n",
    "def reverse_words(sentence):\n",
    "    stack = Stack()\n",
    "    for word in sentence.split():\n",
    "        stack.push(word)\n",
    "\n",
    "    reversed_words = []\n",
    "    while not stack.is_empty():\n",
    "        reversed_words.append(stack.pop())\n",
    "\n",
    "    return \" \".join(reversed_words)\n",
    "\n",
    "\n",
    "print(reverse_words(\"data structures matter\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "queues",
   "metadata": {},
   "source": [
    "## Queues\n",
    "\n",
    "A **queue** is a first-in, first-out (**FIFO**) structure: the item you added earliest is the first one you remove.\n",
    "\n",
    "Common queue operations:\n",
    "\n",
    "- `enqueue(item)`: add an item to the back\n",
    "- `dequeue()`: remove and return the front item\n",
    "- `is_empty()`: check whether the queue has no items\n",
    "\n",
    "A Python list can act as a queue, but removing from its front is slow. `lst.pop(0)` shifts every remaining item one place to the left, so it costs O(n). A `collections.deque` (the double-ended queue from 13.1) is built so that both ends change in O(1) time: `append()` adds at the back and `popleft()` removes from the front. Use a `deque` whenever your code removes items from the front."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-queues",
   "metadata": {},
   "source": [
    "```{index} queue, FIFO, deque.popleft()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "list-vs-deque",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "alice\nalice\n['bob', 'charlie'] ['bob', 'charlie']\n"
    }
   ],
   "source": [
    "from collections import deque\n",
    "\n",
    "waiting_list = [\"alice\", \"bob\", \"charlie\"]\n",
    "waiting_deque = deque([\"alice\", \"bob\", \"charlie\"])\n",
    "\n",
    "print(waiting_list.pop(0))       # alice, after shifting bob and charlie left: O(n)\n",
    "print(waiting_deque.popleft())   # alice, with no shifting: O(1)\n",
    "print(waiting_list, list(waiting_deque))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "queue-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "alice\nbob\n"
    }
   ],
   "source": [
    "from collections import deque\n",
    "\n",
    "\n",
    "class Queue:\n",
    "    def __init__(self):\n",
    "        self._items = deque()\n",
    "\n",
    "    def enqueue(self, item):\n",
    "        self._items.append(item)\n",
    "\n",
    "    def dequeue(self):\n",
    "        if self.is_empty():\n",
    "            raise IndexError(\"dequeue from empty queue\")\n",
    "        return self._items.popleft()\n",
    "\n",
    "    def is_empty(self):\n",
    "        return len(self._items) == 0\n",
    "\n",
    "\n",
    "line = Queue()\n",
    "line.enqueue(\"alice\")\n",
    "line.enqueue(\"bob\")\n",
    "line.enqueue(\"charlie\")\n",
    "\n",
    "print(line.dequeue())\n",
    "print(line.dequeue())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-queue",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Serve a Customer Line\n",
    "# Create a Queue named customers.\n",
    "# 1. Enqueue apple, then banana.\n",
    "# 2. Serve one customer: call dequeue and print the result.\n",
    "# 3. Enqueue cherry.\n",
    "# 4. Serve two more customers, printing each result.\n",
    "# Print exactly:\n",
    "# apple\n",
    "# banana\n",
    "# cherry\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-queue",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "apple\nbanana\ncherry\n"
    }
   ],
   "source": [
    "### Solution\n",
    "customers = Queue()\n",
    "customers.enqueue(\"apple\")\n",
    "customers.enqueue(\"banana\")\n",
    "print(customers.dequeue())\n",
    "\n",
    "customers.enqueue(\"cherry\")\n",
    "print(customers.dequeue())\n",
    "print(customers.dequeue())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "compare",
   "metadata": {},
   "source": [
    "## Stack or Queue?\n",
    "\n",
    "| Problem | Better structure | Reason |\n",
    "| --- | --- | --- |\n",
    "| Undo edits | Stack | Undo the newest action first |\n",
    "| Print jobs | Queue | Print the oldest waiting job first |\n",
    "| Browser back button | Stack | Return to the most recent page |\n",
    "| Help desk tickets | Queue | Serve earlier requests first |\n",
    "| Depth-first search | Stack | Explore one path deeply before backing up |\n",
    "| Breadth-first search | Queue | Explore nearby nodes first |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-compare",
   "metadata": {},
   "source": [
    "```{index} choosing a data structure\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-compare",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Pick the Structure\n",
    "# For each workflow, write \"stack\" or \"queue\" in the dictionary value.\n",
    "# 1. Check that every opening HTML tag, such as <b>, has a matching closing tag\n",
    "# 2. Process sensor readings in the order they arrive\n",
    "# 3. Take coffee orders at a counter\n",
    "# Print exactly:\n",
    "# {'matching HTML tags': 'stack', 'sensor readings': 'queue', 'coffee orders': 'queue'}\n",
    "### Your code starts here.\n",
    "\n",
    "choices = {\n",
    "    \"matching HTML tags\": \"\",\n",
    "    \"sensor readings\": \"\",\n",
    "    \"coffee orders\": \"\",\n",
    "}\n",
    "\n",
    "print(choices)\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-compare",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "{'matching HTML tags': 'stack', 'sensor readings': 'queue', 'coffee orders': 'queue'}\n"
    }
   ],
   "source": [
    "### Solution\n",
    "choices = {\n",
    "    \"matching HTML tags\": \"stack\",   # like balanced brackets: close the newest open tag first\n",
    "    \"sensor readings\": \"queue\",      # oldest reading first\n",
    "    \"coffee orders\": \"queue\",        # first customer served first\n",
    "}\n",
    "\n",
    "print(choices)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
