{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7dfd5639",
   "metadata": {},
   "source": [
    "# Homework\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72fae93e",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**1. Series Labels**\n",
    "\n",
    "A regional sales Series can use store names as index labels instead of only integer positions.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 1 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q1\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q1\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8c5daf11",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.731635Z",
     "iopub.status.busy": "2026-09-16T04:40:33.731257Z",
     "iopub.status.idle": "2026-09-16T04:40:33.736783Z",
     "shell.execute_reply": "2026-09-16T04:40:33.736332Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# Series objects support labeled indexes, which make business values easier to identify.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1cea13d",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**2. DataFrame Column Types**\n",
    "\n",
    "Every column in a pandas DataFrame must use the same data type as every other column.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 2 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q2\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q2\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f218913c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.739122Z",
     "iopub.status.busy": "2026-09-16T04:40:33.738938Z",
     "iopub.status.idle": "2026-09-16T04:40:33.741027Z",
     "shell.execute_reply": "2026-09-16T04:40:33.740681Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# A DataFrame can hold different dtypes in different columns.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2524096a",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**3. Previewing Data**\n",
    "\n",
    "Calling `head()` is mainly used to preview rows; it does not clean or transform the DataFrame by itself.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 3 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q3\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q3\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "17cc8404",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.743059Z",
     "iopub.status.busy": "2026-09-16T04:40:33.742832Z",
     "iopub.status.idle": "2026-09-16T04:40:33.745261Z",
     "shell.execute_reply": "2026-09-16T04:40:33.744697Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# `head()` displays rows so you can inspect a table before analysis.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db8f3ebf",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**4. Missing Data Checks**\n",
    "\n",
    "A manager can use `isna()` to count incomplete values before deciding whether to drop or fill them.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 4 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q4\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q4\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5ea78fd2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.747480Z",
     "iopub.status.busy": "2026-09-16T04:40:33.747311Z",
     "iopub.status.idle": "2026-09-16T04:40:33.749349Z",
     "shell.execute_reply": "2026-09-16T04:40:33.749003Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# `isna()` returns a missing-value mask that can be counted or inspected.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9225157d",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**5. Grouped Summaries**\n",
    "\n",
    "A GroupBy operation can summarize revenue by region only after the data has been converted to a Python list.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 5 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q5\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch04-hw-q5\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d28c6efb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.751170Z",
     "iopub.status.busy": "2026-09-16T04:40:33.751013Z",
     "iopub.status.idle": "2026-09-16T04:40:33.752661Z",
     "shell.execute_reply": "2026-09-16T04:40:33.752391Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# GroupBy works directly on pandas Series and DataFrame objects.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d517c651",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.754047Z",
     "iopub.status.busy": "2026-09-16T04:40:33.753948Z",
     "iopub.status.idle": "2026-09-16T04:40:33.756021Z",
     "shell.execute_reply": "2026-09-16T04:40:33.755743Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 6. Create a Customer Table\n",
    "# Import pandas as pd, then create a DataFrame from names and purchases.\n",
    "# Store the DataFrame in a variable named customers.\n",
    "# Print exactly:\n",
    "# Customer rows: 3\n",
    "# Purchase total: 12\n",
    "names = [\"Ana\", \"Bo\", \"Cy\"]\n",
    "purchases = [5, 3, 4]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "be3e2ee5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.757422Z",
     "iopub.status.busy": "2026-09-16T04:40:33.757314Z",
     "iopub.status.idle": "2026-09-16T04:40:33.959709Z",
     "shell.execute_reply": "2026-09-16T04:40:33.959502Z"
    },
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Customer rows: 3\n",
      "Purchase total: 12\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "names = [\"Ana\", \"Bo\", \"Cy\"]\n",
    "purchases = [5, 3, 4]\n",
    "\n",
    "customers = pd.DataFrame({\"name\": names, \"purchases\": purchases})\n",
    "\n",
    "print(\"Customer rows:\", len(customers))\n",
    "print(\"Purchase total:\", int(customers[\"purchases\"].sum()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ff5ba31e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.960870Z",
     "iopub.status.busy": "2026-09-16T04:40:33.960783Z",
     "iopub.status.idle": "2026-09-16T04:40:33.962113Z",
     "shell.execute_reply": "2026-09-16T04:40:33.961947Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 7. Average Order Value\n",
    "# Import pandas as pd, then create a Series from orders.\n",
    "# Calculate the average order value with mean().\n",
    "# Print exactly:\n",
    "# Average order: 35.0\n",
    "orders = [25, 40, 35, 40]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e9c51317",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.963028Z",
     "iopub.status.busy": "2026-09-16T04:40:33.962968Z",
     "iopub.status.idle": "2026-09-16T04:40:33.964540Z",
     "shell.execute_reply": "2026-09-16T04:40:33.964347Z"
    },
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average order: 35.0\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "orders = [25, 40, 35, 40]\n",
    "\n",
    "order_series = pd.Series(orders)\n",
    "average_order = order_series.mean()\n",
    "\n",
    "print(\"Average order:\", average_order)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1a8a0ae9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.965422Z",
     "iopub.status.busy": "2026-09-16T04:40:33.965355Z",
     "iopub.status.idle": "2026-09-16T04:40:33.966638Z",
     "shell.execute_reply": "2026-09-16T04:40:33.966483Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 8. Select Region Values\n",
    "# Import pandas as pd, then create a DataFrame with region and revenue columns.\n",
    "# Select the West revenue and the first region from the DataFrame.\n",
    "# Print exactly:\n",
    "# West revenue: 900\n",
    "# First region: East\n",
    "rows = [[\"East\", 1200], [\"West\", 900], [\"South\", 700]]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f96ef6b8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.967481Z",
     "iopub.status.busy": "2026-09-16T04:40:33.967433Z",
     "iopub.status.idle": "2026-09-16T04:40:33.969556Z",
     "shell.execute_reply": "2026-09-16T04:40:33.969399Z"
    },
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "West revenue: 900\n",
      "First region: East\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "rows = [[\"East\", 1200], [\"West\", 900], [\"South\", 700]]\n",
    "\n",
    "revenue_df = pd.DataFrame(rows, columns=[\"region\", \"revenue\"])\n",
    "west_revenue = revenue_df.loc[revenue_df[\"region\"] == \"West\", \"revenue\"].iloc[0]\n",
    "first_region = revenue_df.iloc[0][\"region\"]\n",
    "\n",
    "print(\"West revenue:\", int(west_revenue))\n",
    "print(\"First region:\", first_region)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "995ea6ea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.970375Z",
     "iopub.status.busy": "2026-09-16T04:40:33.970333Z",
     "iopub.status.idle": "2026-09-16T04:40:33.971593Z",
     "shell.execute_reply": "2026-09-16T04:40:33.971381Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 9. Fill Missing Ratings\n",
    "# Import pandas as pd, then create a Series from ratings.\n",
    "# Count missing values with isna(), fill missing values with 0, and total the filled Series.\n",
    "# Print exactly:\n",
    "# Missing ratings: 1\n",
    "# Rating total: 8\n",
    "ratings = [5, None, 3]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "cfddc6f5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.972427Z",
     "iopub.status.busy": "2026-09-16T04:40:33.972378Z",
     "iopub.status.idle": "2026-09-16T04:40:33.974210Z",
     "shell.execute_reply": "2026-09-16T04:40:33.974075Z"
    },
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Missing ratings: 1\n",
      "Rating total: 8\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "ratings = [5, None, 3]\n",
    "\n",
    "rating_series = pd.Series(ratings)\n",
    "missing_ratings = int(rating_series.isna().sum())\n",
    "filled_ratings = rating_series.fillna(0)\n",
    "\n",
    "print(\"Missing ratings:\", missing_ratings)\n",
    "print(\"Rating total:\", int(filled_ratings.sum()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ce87576f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.975049Z",
     "iopub.status.busy": "2026-09-16T04:40:33.974995Z",
     "iopub.status.idle": "2026-09-16T04:40:33.976221Z",
     "shell.execute_reply": "2026-09-16T04:40:33.976064Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 10. Match Product Rows\n",
    "# Import pandas as pd, then create a DataFrame with product and price columns.\n",
    "# Filter rows where product is \"pen\" and print the number of matched rows and the pen price.\n",
    "# Print exactly:\n",
    "# Matched rows: 2\n",
    "# Pen price: 2.5\n",
    "products = [[\"pen\", 2.5], [\"notebook\", 4.0], [\"pen\", 2.5]]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "4d65efcd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:33.977032Z",
     "iopub.status.busy": "2026-09-16T04:40:33.976987Z",
     "iopub.status.idle": "2026-09-16T04:40:33.978714Z",
     "shell.execute_reply": "2026-09-16T04:40:33.978553Z"
    },
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matched rows: 2\n",
      "Pen price: 2.5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "products = [[\"pen\", 2.5], [\"notebook\", 4.0], [\"pen\", 2.5]]\n",
    "\n",
    "products_df = pd.DataFrame(products, columns=[\"product\", \"price\"])\n",
    "pen_rows = products_df[products_df[\"product\"] == \"pen\"]\n",
    "pen_price = pen_rows.iloc[0][\"price\"]\n",
    "\n",
    "print(\"Matched rows:\", len(pen_rows))\n",
    "print(\"Pen price:\", pen_price)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "278d5069",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch04-hw-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch04-hw-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch04-hw-feedback-list[hidden] { display: none; }\n",
    ".ch04-hw-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch04-hw-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch04-hw-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch04-hw-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch04-hw-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch04-hw-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch04-hw-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch04-hw-actions.is-locked { opacity: 0.55; }\n",
    ".ch04-hw-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch04-hw-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch04-hw-grader' id='ch04-hw-grader'>\n",
    "  <div class='ch04-hw-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q6'><strong>Question 6</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q7'><strong>Question 7</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q8'><strong>Question 8</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q9'><strong>Question 9</strong><span></span></div>\n",
    "    <div class='ch04-hw-feedback-row' data-question='q10'><strong>Question 10</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch04-hw-actions'>\n",
    "    <button type='button' id='ch04-hw-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch04-hw-reset'>Clear Results</button>\n",
    "    <span class='ch04-hw-result' id='ch04-hw-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var homeworkId = 'ch04-homework';\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",
    "\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 cm = cell.querySelector('.CodeMirror');\n",
    "    if (cm && cm.CodeMirror && typeof cm.CodeMirror.getValue === 'function') return cm.CodeMirror.getValue();\n",
    "    var cmContent = cell.querySelector('.cm-content');\n",
    "    if (cmContent && cmContent.cmView && cmContent.cmView.view) return cmContent.cmView.view.state.doc.toString();\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.prototype.slice.call(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n",
    "    var code = {};\n",
    "    cells.forEach(function (cell, index) {\n",
    "      code['q' + (index + 6)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function collectAnswers() {\n",
    "    var answers = {};\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n",
    "      var checked = document.querySelector('input[name=\"ch04-hw-' + question + '\"]:checked');\n",
    "      answers[question] = checked ? checked.value : '';\n",
    "    });\n",
    "    return answers;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch04-hw-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10'].forEach(function (question) {\n",
    "      var row = grader.querySelector('[data-question=' + question + ']');\n",
    "      var message = row.querySelector('span');\n",
    "      var item = feedback[question];\n",
    "      row.className = 'ch04-hw-feedback-row';\n",
    "      if (!item) return;\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('.ch04-hw-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch04-hw-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch04-hw-feedback-row';\n",
    "      var message = row.querySelector('span');\n",
    "      if (message) message.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function saveAttempt(payload) {\n",
    "    return fetch('/api/v1/homework-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 payload = text ? JSON.parse(text) : null;\n",
    "        if (!payload || !response.ok || !payload.ok) {\n",
    "          throw new Error((payload && (payload.message || payload.error)) || 'Submission API is unavailable.');\n",
    "        }\n",
    "        return payload;\n",
    "      });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function initHomeworkGrader() {\n",
    "    var grader = document.getElementById('ch04-hw-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch04-hw-actions');\n",
    "    var result = document.getElementById('ch04-hw-result');\n",
    "    var submit = document.getElementById('ch04-hw-submit');\n",
    "    var reset = document.getElementById('ch04-hw-reset');\n",
    "\n",
    "    loadSessionIdentity(identity, actions, submit, result);\n",
    "\n",
    "    submit.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Submitting homework.';\n",
    "\n",
    "      saveAttempt({\n",
    "        homework_id: homeworkId,\n",
    "        answers: collectAnswers(),\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",
    "          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",
    "          applyFeedback(grader, payload.feedback || {});\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', initHomeworkGrader);\n",
    "  } else {\n",
    "    initHomeworkGrader();\n",
    "  }\n",
    "})();\n",
    "</script>\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
