{
 "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=\"ch04-lab\"></div>\n",
   "id": "ch04-lab-intro"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Default parameters\n",
    "# Write format_invoice(amount, currency=\"USD\") that returns a string like\n",
    "# \"120.00 USD\", formatting amount to 2 decimal places.\n",
    "# Call it once without currency and once passing currency=\"EUR\".\n",
    "# Print exactly these two lines:\n",
    "# 120.00 USD\n",
    "# 85.50 EUR\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch04-lab-q1"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: Flexible arguments with *args and **kwargs\n",
    "# Write trip_summary(destination, *stops, **details) that returns a dictionary\n",
    "# with keys \"destination\", \"stops\" (a tuple), and \"details\" (a dict).\n",
    "# Call it with destination=\"Denver\", stops \"Omaha\" and \"Boulder\",\n",
    "# and keyword details days=5, budget=900. Print the returned dictionary.\n",
    "# Print exactly this line:\n",
    "# {'destination': 'Denver', 'stops': ('Omaha', 'Boulder'), 'details': {'days': 5, 'budget': 900}}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch04-lab-q2"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: Function composition for a BMI report\n",
    "# Write three functions:\n",
    "# 1. compute_bmi(weight_kg, height_m): returns weight_kg / height_m ** 2\n",
    "# 2. bmi_category(bmi): returns \"underweight\" if bmi < 18.5,\n",
    "#    \"healthy\" if bmi < 25, otherwise \"above healthy range\"\n",
    "# 3. bmi_report(weight_kg, height_m): calls both and returns\n",
    "#    \"BMI is X.X (category)\", with bmi rounded to 1 decimal place\n",
    "# Call bmi_report(70, 1.75) and bmi_report(90, 1.70), printing each result.\n",
    "# Print exactly these two lines:\n",
    "# BMI is 22.9 (healthy)\n",
    "# BMI is 31.1 (above healthy range)\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch04-lab-q3"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Pure function refactor\n",
    "# apply_discount_in_place(prices, percent) below mutates its list argument.\n",
    "# Write a pure version, apply_discount(prices, percent), that returns a NEW\n",
    "# list of prices reduced by percent (each rounded to 2 decimals) without\n",
    "# changing the original list.\n",
    "# Call apply_discount(cart_prices, 10) and store the result in discounted.\n",
    "# Print cart_prices, then discounted.\n",
    "# Print exactly these two lines:\n",
    "# [40.0, 15.0, 60.0]\n",
    "# [36.0, 13.5, 54.0]\n",
    "def apply_discount_in_place(prices, percent):\n",
    "    for i in range(len(prices)):\n",
    "        prices[i] = round(prices[i] * (1 - percent / 100), 2)\n",
    "\n",
    "cart_prices = [40.0, 15.0, 60.0]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch04-lab-q4"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Recursion over a list\n",
    "# Write list_product(nums), which returns the product of all numbers in nums,\n",
    "# using recursion. The product of an empty list is 1; otherwise multiply the\n",
    "# first item by the recursive product of the rest of the list.\n",
    "# Print exactly these two lines:\n",
    "# 24\n",
    "# 5\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch04-lab-q5"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "<style>\n.ch04-lab-grader { max-width: 900px; margin-top: 1rem; }\n.ch04-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n.ch04-lab-feedback-list[hidden] { display: none; }\n.ch04-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n.ch04-lab-feedback-row strong { margin-right: 0.35rem; }\n.ch04-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n.ch04-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n.ch04-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n.ch04-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.ch04-lab-actions button.secondary { background: white; color: #176de8; }\n.ch04-lab-actions.is-locked { opacity: 0.55; }\n.ch04-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n.ch04-lab-result { font-weight: 700; }\n</style>\n\n<div class='ch04-lab-grader' id='ch04-lab-grader'>\n  <div class='ch04-lab-feedback-list' aria-live='polite' hidden>\n    <div class='ch04-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n    <div class='ch04-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n    <div class='ch04-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n    <div class='ch04-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n    <div class='ch04-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n  </div>\n  <div class='ch04-lab-actions'>\n    <button type='button' id='ch04-lab-submit' disabled>Submit</button>\n    <button type='button' class='secondary' id='ch04-lab-reset'>Clear Results</button>\n    <span class='ch04-lab-result' id='ch04-lab-result' aria-live='polite'></span>\n  </div>\n</div>\n\n<script>\n(function () {\n  var labId = 'ch04-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('.ch04-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('.ch04-lab-feedback-list');\n    if (list) list.hidden = true;\n    grader.querySelectorAll('.ch04-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('ch04-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('ch04-lab-result');\n    var submit = document.getElementById('ch04-lab-submit');\n    var actions = grader.querySelector('.ch04-lab-actions');\n    var reset = document.getElementById('ch04-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": "ch04-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
}