{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Lab\n\n- Use this assignment to practice the chapter's concepts and coding skills in runnable Python code.\n- Sign in from the account menu before you start working on the assignment.\n- Write and run your code directly in the coding cells.\n- Multiple submissions are allowed. The highest score is kept.\n\n<div data-assignment-answers=\"ch13-lab\"></div>\n",
   "id": "ch13-lab-intro"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Stack Class: Browsing History\n",
    "# Implement a `Stack` class backed by a list, with:\n",
    "# - `push(item)`: add `item` to the top of the stack\n",
    "# - `pop()`: remove and return the top item (LIFO order)\n",
    "# - `peek()`: return the top item without removing it\n",
    "# - `__len__`: number of items currently on the stack, so `len(history)`\n",
    "#   works (the special method from 9.3, Operator Overloading)\n",
    "# Push `'home'`, then `'products'`, then `'checkout'` onto a `Stack` named `history`\n",
    "# with `push()`.\n",
    "# Pop twice and print each popped value, then print `len(history)`.\n",
    "# Print exactly these three lines:\n",
    "# checkout\n",
    "# products\n",
    "# 1\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch13-lab-q1"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: Queue Class: Serve a Customer Line\n",
    "# Import `deque` with: `from collections import deque`\n",
    "# Implement a `Queue` class backed by a `deque`, with:\n",
    "# - `enqueue(item)`: add `item` to the back of the line\n",
    "# - `dequeue()`: remove and return the item at the front (FIFO order);\n",
    "#   use `self.items.popleft()` so removal happens from the front\n",
    "# - `__len__`: number of items currently waiting, so `len(customers)` works\n",
    "# Enqueue `'apple'`, `'banana'`, `'cherry'` in a `Queue` named `customers`.\n",
    "# Serve two customers by calling `dequeue()` twice and print each result,\n",
    "# then print `len(customers)`.\n",
    "# Print exactly these three lines:\n",
    "# apple\n",
    "# banana\n",
    "# 1\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch13-lab-q2"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: Add a Node to an Org-Chart Tree\n",
    "# `org_chart` is built from the `TreeNode` class taught in 13.3: each node\n",
    "# has a `value` (the employee name) and a `children` list, and\n",
    "# `add_child(child)` appends a child node.\n",
    "# Write `add_employee(node, manager_name, new_name)` that searches the\n",
    "# tree recursively for the node whose `value` is `manager_name`, and, once\n",
    "# found, adds `TreeNode(new_name)` to that manager with `add_child`.\n",
    "# Return `True` once added, `False` if the manager was never found\n",
    "# (search the rest of the tree recursively otherwise).\n",
    "# Write `list_names(node)` that returns a flat list of every `value` in\n",
    "# the tree, visiting a node before its children (root first).\n",
    "# Call `add_employee(org_chart, 'charlie', 'erin')`, then print\n",
    "# `list_names(org_chart)` exactly:\n",
    "# ['operations', 'charlie', 'erin', 'dana']\n",
    "class TreeNode:\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "        self.children = []\n",
    "\n",
    "    def add_child(self, child):\n",
    "        self.children.append(child)\n",
    "\n",
    "\n",
    "org_chart = TreeNode(\"operations\")\n",
    "org_chart.add_child(TreeNode(\"charlie\"))\n",
    "org_chart.add_child(TreeNode(\"dana\"))\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch13-lab-q3"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Breadth-First Traversal of a Graph\n",
    "# `graph` is an adjacency-list `dict` mapping each person to their\n",
    "# connections. Write `bfs_order(graph, start)` that performs a\n",
    "# breadth-first traversal starting at `start` and returns the list of\n",
    "# names in the order they were first visited.\n",
    "# Use a `deque` as the queue (`from collections import deque`; `append` to\n",
    "# enqueue, `popleft()` to dequeue) and a `set` named `visited` to track\n",
    "# visited names (use the `in` operator to test whether a name is new).\n",
    "# Call `bfs_order(graph, 'alice')`.\n",
    "# Print exactly:\n",
    "# ['alice', 'bob', 'charlie', 'dana', 'erin']\n",
    "graph = {\n",
    "    \"alice\": [\"bob\", \"charlie\"],\n",
    "    \"bob\": [\"alice\", \"dana\"],\n",
    "    \"charlie\": [\"alice\", \"dana\"],\n",
    "    \"dana\": [\"bob\", \"charlie\", \"erin\"],\n",
    "    \"erin\": [\"dana\"],\n",
    "}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch13-lab-q4"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Pick the Right Structure\n",
    "# For each workload description below, assign the best-fitting\n",
    "# Python structure as a string: `'list'`, `'set'`, `'dict'`, `'queue'`, or\n",
    "# `'stack'`.\n",
    "# Fill in each value in the `workload` dict, then print `workload`.\n",
    "# Print exactly this dict:\n",
    "# {'process refund requests in the order received': 'queue', 'undo the last edit in a text editor': 'stack', 'track unique visitor IDs seen today': 'set', 'look up an account plan by username': 'dict'}\n",
    "workload = {\n",
    "    \"process refund requests in the order received\": \"\",\n",
    "    \"undo the last edit in a text editor\": \"\",\n",
    "    \"track unique visitor IDs seen today\": \"\",\n",
    "    \"look up an account plan by username\": \"\",\n",
    "}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch13-lab-q5"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "<style>\n.ch13-lab-grader { max-width: 900px; margin-top: 1rem; }\n.ch13-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n.ch13-lab-feedback-list[hidden] { display: none; }\n.ch13-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n.ch13-lab-feedback-row strong { margin-right: 0.35rem; }\n.ch13-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n.ch13-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n.ch13-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n.ch13-lab-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n.ch13-lab-actions button.secondary { background: white; color: #176de8; }\n.ch13-lab-actions.is-locked { opacity: 0.55; }\n.ch13-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n.ch13-lab-result { font-weight: 700; }\n</style>\n\n<div class='ch13-lab-grader' id='ch13-lab-grader'>\n  <div class='ch13-lab-feedback-list' aria-live='polite' hidden>\n    <div class='ch13-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n    <div class='ch13-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n    <div class='ch13-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n    <div class='ch13-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n    <div class='ch13-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n  </div>\n  <div class='ch13-lab-actions'>\n    <button type='button' id='ch13-lab-submit' disabled>Submit</button>\n    <button type='button' class='secondary' id='ch13-lab-reset'>Clear Results</button>\n    <span class='ch13-lab-result' id='ch13-lab-result' aria-live='polite'></span>\n  </div>\n</div>\n\n<script>\n(function () {\n  var labId = 'ch13-lab';\n\n  function getParams() {\n    var params = new URLSearchParams(window.location.search);\n    return {\n      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n    };\n  }\n\n  function loadSessionIdentity(identity, actions, submit, result) {\n    submit.disabled = true;\n    actions.classList.add('is-locked');\n    result.textContent = 'Sign in from the account menu to submit this assignment.';\n    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n      .then(function (response) { return response.ok ? response.json() : null; })\n      .then(function (payload) {\n        if (!payload || !payload.authenticated || !payload.identity) return identity;\n        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n        identity.student_identifier = payload.identity.student_identifier || '';\n        submit.disabled = false;\n        actions.classList.remove('is-locked');\n        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n        return identity;\n      })\n      .catch(function () { return identity; });\n  }\n\n  function codeFromCell(cell) {\n    var codeMirror = cell.querySelector('.CodeMirror');\n    if (codeMirror && codeMirror.CodeMirror && typeof codeMirror.CodeMirror.getValue === 'function') {\n      return codeMirror.CodeMirror.getValue();\n    }\n    var cmContent = cell.querySelector('.cm-content');\n    if (cmContent) {\n      return Array.from(cmContent.querySelectorAll('.cm-line')).map(function (line) { return line.textContent; }).join('\\n');\n    }\n    var textarea = cell.querySelector('textarea');\n    if (textarea) return textarea.value;\n    var pre = cell.querySelector('.cell_input pre');\n    return pre ? pre.textContent : '';\n  }\n\n  function collectCodeCells() {\n    var cells = Array.from(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n    var code = {};\n    cells.forEach(function (cell, index) {\n      code['q' + (index + 1)] = codeFromCell(cell);\n    });\n    return code;\n  }\n\n  function applyFeedback(grader, feedback) {\n    var list = grader.querySelector('.ch13-lab-feedback-list');\n    if (list) list.hidden = false;\n    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n      var row = grader.querySelector('[data-question=' + question + ']');\n      var message = row ? row.querySelector('span') : null;\n      var item = feedback ? feedback[question] : null;\n      if (!row || !message || !item) return;\n      row.classList.remove('correct', 'incorrect');\n      message.textContent = item.message + ' (' + item.score + ' / ' + item.max_score + ')';\n      row.classList.add(item.correct ? 'correct' : 'incorrect');\n    });\n  }\n\n  function clearFeedback(grader) {\n    var list = grader.querySelector('.ch13-lab-feedback-list');\n    if (list) list.hidden = true;\n    grader.querySelectorAll('.ch13-lab-feedback-row').forEach(function (row) {\n      row.classList.remove('correct', 'incorrect');\n      var message = row.querySelector('span');\n      if (message) message.textContent = '';\n    });\n  }\n\n  function saveAttempt(payload) {\n    return fetch('/api/v1/lab-attempts.php', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      credentials: 'same-origin',\n      body: JSON.stringify(payload)\n    }).then(function (response) {\n      return response.text().then(function (text) {\n        var saved = text ? JSON.parse(text) : null;\n        if (!response.ok || !saved || !saved.ok) throw new Error(saved && (saved.message || saved.error) ? (saved.message || saved.error) : 'Submission API is unavailable.');\n        return saved;\n      });\n    });\n  }\n\n  function initLabGrader() {\n    var grader = document.getElementById('ch13-lab-grader');\n    if (!grader || grader.dataset.ready === 'true') return;\n    grader.dataset.ready = 'true';\n\n    var identity = getParams();\n    var result = document.getElementById('ch13-lab-result');\n    var submit = document.getElementById('ch13-lab-submit');\n    var actions = grader.querySelector('.ch13-lab-actions');\n    var reset = document.getElementById('ch13-lab-reset');\n\n    loadSessionIdentity(identity, actions, submit, result);\n\n    submit.addEventListener('click', function () {\n      clearFeedback(grader);\n      result.textContent = 'Submitting code.';\n      submit.disabled = true;\n      saveAttempt({\n        lab_id: labId,\n        code: collectCodeCells(),\n        canvas_course_id: identity.canvas_course_id,\n        canvas_assignment_id: identity.canvas_assignment_id,\n        canvas_user_id: identity.canvas_user_id\n      })\n        .then(function (payload) {\n          if (payload.feedback) applyFeedback(grader, payload.feedback);\n          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n        })\n        .catch(function (error) {\n          result.textContent = 'Could not save this attempt: ' + error.message;\n        })\n        .finally(function () {\n          submit.disabled = false;\n        });\n    });\n\n    reset.addEventListener('click', function () {\n      clearFeedback(grader);\n      result.textContent = '';\n    });\n  }\n\n  if (document.readyState === 'loading') {\n    document.addEventListener('DOMContentLoaded', initLabGrader);\n  } else {\n    initLabGrader();\n  }\n})();\n</script>",
   "id": "ch13-lab-submit-block"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11.0"
  },
  "press_solutions_stripped": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}