{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "hw-00",
   "metadata": {},
   "source": "# Homework\n\nApply the chapter to new text inputs. Each coding cell must define the named function and run independently. Grading checks the printed example and alternate inputs, including malformed and empty cases.\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<style>\n.tf-options { display: flex; gap: 1.25rem; flex-wrap: wrap; margin: 0.4rem 0 0.15rem; font-size: inherit !important; }\n.tf-options label { display: inline-flex; align-items: center; gap: 0.35rem; cursor: pointer; font-size: inherit !important; font-weight: 400 !important; line-height: 1.4; }\n.tf-options input { margin: 0; }\n.cell:has(.tf-options) { margin-bottom: 0.1rem; }\n.cell:has(.tf-options) + .cell { margin-top: 0; margin-bottom: 1.65rem; }\n.cell:has(.tf-options) + .cell details { margin-top: 0; }\n</style>\n\n<div data-assignment-answers=\"ch08-homework\"></div>\n"
  },
  {
   "cell_type": "markdown",
   "id": "hw-01",
   "metadata": {},
   "source": "::::{div} assignment-question-card\n\n**1. String Immutability**\n\nA report stores raw text for later review. Assigning the result of strip() to a new variable preserves the original string.\n\n<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 1 answer\">\n  <label><input type=\"radio\" name=\"ch08-hw-q1\" value=\"true\"> True</label>\n  <label><input type=\"radio\" name=\"ch08-hw-q1\" value=\"false\"> False</label>\n</div>\n\n::::\n"
  },
  {
   "cell_type": "markdown",
   "id": "hw-03",
   "metadata": {},
   "source": "::::{div} assignment-question-card\n\n**2. Numeric Conversion**\n\nA script checks user_input.isdigit() before calling int(user_input). This guarantees that the conversion will succeed.\n\n<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 2 answer\">\n  <label><input type=\"radio\" name=\"ch08-hw-q2\" value=\"true\"> True</label>\n  <label><input type=\"radio\" name=\"ch08-hw-q2\" value=\"false\"> False</label>\n</div>\n\n::::\n"
  },
  {
   "cell_type": "markdown",
   "id": "hw-05",
   "metadata": {},
   "source": "::::{div} assignment-question-card\n\n**3. Whitespace Policy**\n\nA pipeline intentionally collapses repeated spaces by splitting on whitespace and joining with one space. Its result may differ from the original text.\n\n<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 3 answer\">\n  <label><input type=\"radio\" name=\"ch08-hw-q3\" value=\"true\"> True</label>\n  <label><input type=\"radio\" name=\"ch08-hw-q3\" value=\"false\"> False</label>\n</div>\n\n::::\n"
  },
  {
   "cell_type": "markdown",
   "id": "hw-07",
   "metadata": {},
   "source": "::::{div} assignment-question-card\n\n**4. Whole-ID Validation**\n\nA validator accepts an employee ID whenever re.match() finds the required prefix, even when extra characters follow it. This validates the entire ID.\n\n<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 4 answer\">\n  <label><input type=\"radio\" name=\"ch08-hw-q4\" value=\"true\"> True</label>\n  <label><input type=\"radio\" name=\"ch08-hw-q4\" value=\"false\"> False</label>\n</div>\n\n::::\n"
  },
  {
   "cell_type": "markdown",
   "id": "hw-09",
   "metadata": {},
   "source": "::::{div} assignment-question-card\n\n**5. Successor Probabilities**\n\nA successor list contains sat twice and slept once. Choosing a list position uniformly makes sat twice as likely as slept.\n\n<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 5 answer\">\n  <label><input type=\"radio\" name=\"ch08-hw-q5\" value=\"true\"> True</label>\n  <label><input type=\"radio\" name=\"ch08-hw-q5\" value=\"false\"> False</label>\n</div>\n\n::::\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw-11",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 6: Normalize and document a label\n",
    "# Define normalize_label(text: str) -> str, with a docstring describing its parameter,\n",
    "# return value, and ValueError. Strip outer whitespace, reject an empty result with\n",
    "# ValueError, and return the casefolded label. Print the supplied label's result.\n",
    "# Print exactly:\n",
    "# Label: strasse\n",
    "label = '  Straße  '\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw-13",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 7: Compare tokenization policies\n",
    "# Define tokenize(text, split_hyphens=False). Use the lab's boundary punctuation\n",
    "# . , ! ? ; : \" ( ), lowercase, replace em dashes with spaces, and discard empty tokens.\n",
    "# Preserve internal hyphens unless split_hyphens is True; then replace them with spaces.\n",
    "# Print both token lists. This question must run without executing the lab.\n",
    "# Print exactly:\n",
    "# Keep hyphens: ['data', 'data', 'pocket-handkerchief']\n",
    "# Split hyphens: ['data', 'data', 'pocket', 'handkerchief']\n",
    "text = 'DATA, data! pocket-handkerchief !!!'\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw-15",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 8: Extract ticket-specific captures\n",
    "# Define ticket_numbers(message) to return strings captured from ticket mentions:\n",
    "# the whole word Ticket (case-insensitive), one space, then one or more ASCII digits\n",
    "# ending at a word boundary. Use a capturing group with re.findall().\n",
    "# Ignore unrelated dates and room numbers. Print the list from message.\n",
    "# Print exactly:\n",
    "# Ticket numbers: ['12', '105']\n",
    "message = 'On 2024-03-15, Ticket 12 moved before ticket 105; room 7.'\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw-17",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 9: Verify equivalent frequency reports\n",
    "# Define frequencies(text) to return a manual word-count dictionary. Split on whitespace,\n",
    "# strip boundary punctuation . , ! ? ; : \" ( ), lowercase, and discard empty results.\n",
    "# Independently build counter_counts with Counter on a cleaned token list using the same\n",
    "# policy. Print the manual counts and whether the two dictionaries agree.\n",
    "# Do not import a function from another question.\n",
    "# Print exactly:\n",
    "# Counts: {'python': 2, 'data': 1}\n",
    "# Agree: True\n",
    "text = 'Python, data PYTHON! !!!'\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw-19",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 10: Model repeated successors and stop safely\n",
    "# Define build_successors(sentence) to map each whitespace-separated word to its list\n",
    "# of following words, keeping repetitions. Do not add an entry solely for a final word.\n",
    "# Define generate(successor_map, word, length) to return at most length words, including\n",
    "# the start. Choose the FIRST successor deterministically (this tests traversal, not\n",
    "# random generation). Stop on a missing or empty successor list. length is a positive int.\n",
    "# Print the successors of \"cat\", the probability of \"sat\" given \"cat\" to two decimals,\n",
    "# and the two deterministic sequences shown below. Compute probability from the list.\n",
    "# Print exactly:\n",
    "# Successors of cat: ['sat', 'sat', 'slept']\n",
    "# P(sat | cat): 0.67\n",
    "# From cat: cat sat cat sat cat sat\n",
    "# From slept: slept\n",
    "sentence = 'cat sat cat sat cat slept'\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw-21",
   "metadata": {},
   "source": "<style>\n.ch08-homework-submit { max-width: 900px; margin-top: 1rem; }\n.ch08-homework-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n.ch08-homework-feedback-list[hidden] { display: none; }\n.ch08-homework-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n.ch08-homework-feedback-row strong { margin-right: 0.35rem; }\n.ch08-homework-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n.ch08-homework-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n.ch08-homework-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n.ch08-homework-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n.ch08-homework-actions button.secondary { background: white; color: #176de8; }\n.ch08-homework-actions.is-locked { opacity: 0.55; }\n.ch08-homework-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n.ch08-homework-result { font-weight: 700; }\n</style>\n\n<div class='ch08-homework-submit' id='ch08-homework-submit-panel'>\n  <div class='ch08-homework-feedback-list' aria-live='polite' hidden>\n    <div class='ch08-homework-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q6'><strong>Question 6</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q7'><strong>Question 7</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q8'><strong>Question 8</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q9'><strong>Question 9</strong><span></span></div>\n    <div class='ch08-homework-feedback-row' data-question='q10'><strong>Question 10</strong><span></span></div>\n  </div>\n  <div class='ch08-homework-actions'>\n    <button type='button' id='ch08-homework-submit' disabled>Submit</button>\n    <button type='button' class='secondary' id='ch08-homework-reset'>Clear Results</button>\n    <span class='ch08-homework-result' id='ch08-homework-result' aria-live='polite'></span>\n  </div>\n</div>\n\n<script>\n(function () {\n  var homeworkId = 'ch08-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    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 + 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 selected = document.querySelector('input[name=ch08-hw-' + question + ']:checked');\n      answers[question] = selected ? selected.value : '';\n    });\n    return answers;\n  }\n\n  function applyFeedback(panel, feedback) {\n    var list = panel.querySelector('.ch08-homework-feedback-list');\n    if (list) list.hidden = false;\n    ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10'].forEach(function (question) {\n      var row = panel.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(panel) {\n    var list = panel.querySelector('.ch08-homework-feedback-list');\n    if (list) list.hidden = true;\n    panel.querySelectorAll('.ch08-homework-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/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 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 initHomeworkSubmit() {\n    var panel = document.getElementById('ch08-homework-submit-panel');\n    if (!panel || panel.dataset.ready === 'true') return;\n    panel.dataset.ready = 'true';\n\n    var identity = getParams();\n    var result = document.getElementById('ch08-homework-result');\n    var submit = document.getElementById('ch08-homework-submit');\n    var actions = panel.querySelector('.ch08-homework-actions');\n    var reset = document.getElementById('ch08-homework-reset');\n\n    loadSessionIdentity(identity, actions, submit, result);\n\n    submit.addEventListener('click', function () {\n      clearFeedback(panel);\n      result.textContent = 'Submitting homework.';\n      submit.disabled = true;\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          if (payload.feedback) applyFeedback(panel, 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(panel);\n      result.textContent = '';\n    });\n  }\n\n  if (document.readyState === 'loading') {\n    document.addEventListener('DOMContentLoaded', initHomeworkSubmit);\n  } else {\n    initHomeworkSubmit();\n  }\n})();\n</script>\n"
  }
 ],
 "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
}