{ "cells": [ { "cell_type": "markdown", "id": "cba06bar", "metadata": {}, "source": [ "\n", "**Other Ways to open this chapter:** \n", "[JupyterLite](https://python.porttack.com/jupyterlite-3db08322a4/notebooks/index.html?path=Chapter06-Return-Values.ipynb) | \n", "[Colab](https://colab.research.google.com/github/porttack/working-in-python/blob/v3/chapters/chap06.ipynb) | \n", "[Read Only](https://python.porttack.com/chap06.html?readonly) | \n", "Download\n", "\n", "" ] }, { "cell_type": "markdown", "id": "cba06pane", "metadata": {}, "source": [ "\n", "

Ignore this cell — used when running JupyterLite.

\n", "\n", "\n", "
\n", "\n", "
\n", "\n", "" ] }, { "cell_type": "code", "execution_count": 5, "id": "56b1c184", "metadata": { "tags": [] }, "outputs": [], "source": [ "from os.path import basename, exists\n", "\n", "def download(url):\n", " \"\"\"Download a file if it isn't already here, and return its filename.\"\"\"\n", " filename = basename(url)\n", " if not exists(filename):\n", " from urllib.request import urlretrieve\n", "\n", " local, _ = urlretrieve(url, filename)\n", " print(\"Downloaded \" + str(local))\n", " return filename\n", "\n", "download('https://github.com/porttack/working-in-python/raw/v3/working_in_python.py');\n", "download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');\n", "\n", "import working_in_python" ] }, { "cell_type": "markdown", "id": "88ecc443", "metadata": {}, "source": [ "# Return Values\n", "\n", "In previous chapters, we've used built-in functions -- like `abs` and `round` -- and functions in the math module -- like `sqrt` and `pow`.\n", "When you call one of these functions, it returns a value you can assign to a variable or use as part of an expression.\n", "\n", "The functions we have written so far are different.\n", "Some use the `print` function to display values, and some use turtle functions to draw figures.\n", "But they don't return values we assign to variables or use in expressions.\n", "\n", "In this chapter, we'll see how to write functions that return values." ] }, { "cell_type": "markdown", "id": "6cf2cf80", "metadata": {}, "source": [ "## Some functions have return values\n", "\n", "When you call a function like `math.sqrt`, the result is called a **return value**.\n", "If the function call appears at the end of a cell, Jupyter displays the return value immediately." ] }, { "cell_type": "code", "execution_count": 6, "id": "e0e1dd91", "metadata": {}, "outputs": [], "source": [ "import math\n", "\n", "math.sqrt(42 / math.pi)" ] }, { "cell_type": "markdown", "id": "4b4885c2", "metadata": {}, "source": [ "If you assign the return value to a variable, it doesn't get displayed." ] }, { "cell_type": "code", "execution_count": 7, "id": "5aaf62d2", "metadata": {}, "outputs": [], "source": [ "radius = math.sqrt(42 / math.pi)" ] }, { "cell_type": "markdown", "id": "196c692b", "metadata": {}, "source": [ "But you can display it later." ] }, { "cell_type": "code", "execution_count": 8, "id": "741f7386", "metadata": {}, "outputs": [], "source": [ "radius" ] }, { "cell_type": "markdown", "id": "257b28d5", "metadata": {}, "source": [ "Or you can use the return value as part of an expression." ] }, { "cell_type": "code", "execution_count": 9, "id": "e56d39c4", "metadata": {}, "outputs": [], "source": [ "radius + math.sqrt(42 / math.pi)" ] }, { "cell_type": "markdown", "id": "23ed47ab", "metadata": {}, "source": [ "Here's an example of a function that returns a value." ] }, { "cell_type": "code", "execution_count": 10, "id": "50a9a9be", "metadata": {}, "outputs": [], "source": [ "def circle_area(radius):\n", " area = math.pi * radius**2\n", " return area" ] }, { "cell_type": "markdown", "id": "273acabc", "metadata": {}, "source": [ "`circle_area` takes `radius` as a parameter and computes the area of a circle with that radius.\n", "\n", "The last line is a `return` statement that returns the value of `area`.\n", "\n", "If we call the function like this, Jupyter displays the return value.\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "d70fd9b5", "metadata": {}, "outputs": [], "source": [ "circle_area(radius)" ] }, { "cell_type": "markdown", "id": "4f28bfd6", "metadata": {}, "source": [ "We can assign the return value to a variable." ] }, { "cell_type": "code", "execution_count": 12, "id": "ef20ba8c", "metadata": {}, "outputs": [], "source": [ "a = circle_area(radius)" ] }, { "cell_type": "markdown", "id": "3f82fe70", "metadata": {}, "source": [ "Or use it as part of an expression." ] }, { "cell_type": "code", "execution_count": 13, "id": "0a4670f4", "metadata": {}, "outputs": [], "source": [ "circle_area(radius) + 2 * circle_area(radius / 2)" ] }, { "cell_type": "markdown", "id": "15122fd2", "metadata": {}, "source": [ "Later we can display the value of the variable we assigned the result to." ] }, { "cell_type": "code", "execution_count": 14, "id": "6e6460b9", "metadata": {}, "outputs": [], "source": [ "a" ] }, { "cell_type": "markdown", "id": "a3f6dcae", "metadata": {}, "source": [ "But we can't access `area`.\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "77613df9", "metadata": { "tags": [] }, "outputs": [], "source": [ "\n", "area" ] }, { "cell_type": "markdown", "id": "f8ace9ce", "metadata": {}, "source": [ "`area` is a local variable in a function, so we can't access it from outside the function." ] }, { "cell_type": "markdown", "id": "41a4f03f", "metadata": {}, "source": [ "## And some have None\n", "\n", "If a function doesn't have a `return` statement, it returns `None`, which is a special value like `True` and `False`.\n", "For example, here's the `repeat` function from Chapter 3." ] }, { "cell_type": "code", "execution_count": 16, "id": "89c083f8", "metadata": {}, "outputs": [], "source": [ "def repeat(word, n):\n", " print(word * n)" ] }, { "cell_type": "markdown", "id": "6ada19cf", "metadata": {}, "source": [ "If we call it like this, it displays the first line of the Monty Python song \"Finland\"." ] }, { "cell_type": "code", "execution_count": 17, "id": "737b67ca", "metadata": {}, "outputs": [], "source": [ "repeat('Finland, ', 3)" ] }, { "cell_type": "markdown", "id": "fe49f5e5", "metadata": {}, "source": [ "This function uses the `print` function to display a string, but it does not use a `return` statement to return a value.\n", "If we assign the result to a variable, it displays the string anyway. " ] }, { "cell_type": "code", "execution_count": 18, "id": "9b4fa14f", "metadata": {}, "outputs": [], "source": [ "result = repeat('Finland, ', 3)" ] }, { "cell_type": "markdown", "id": "4ecabbdb", "metadata": {}, "source": [ "And if we display the value of the variable, we get nothing." ] }, { "cell_type": "code", "execution_count": 19, "id": "50f96bcb", "metadata": {}, "outputs": [], "source": [ "result" ] }, { "cell_type": "markdown", "id": "07033959", "metadata": {}, "source": [ "`result` actually has a value, but Jupyter doesn't show it.\n", "However, we can display it like this." ] }, { "cell_type": "code", "execution_count": 20, "id": "6712f2df", "metadata": {}, "outputs": [], "source": [ "print(result)" ] }, { "cell_type": "markdown", "id": "379b98c5", "metadata": {}, "source": [ "The return value from `repeat` is `None`.\n", "\n", "Now here's a function similar to `repeat` except that has a return value." ] }, { "cell_type": "code", "execution_count": 21, "id": "0ec1afd3", "metadata": {}, "outputs": [], "source": [ "def repeat_string(word, n):\n", " return word * n" ] }, { "cell_type": "markdown", "id": "db6ad3d4", "metadata": {}, "source": [ "Notice that we can use an expression in a `return` statement, not just a variable.\n", "\n", "With this version, we can assign the result to a variable.\n", "When the function runs, it doesn't display anything." ] }, { "cell_type": "code", "execution_count": 22, "id": "c82334b6", "metadata": {}, "outputs": [], "source": [ "line = repeat_string('Spam, ', 4)" ] }, { "cell_type": "markdown", "id": "1232cd8a", "metadata": {}, "source": [ "But later we can display the value assigned to `line`." ] }, { "cell_type": "code", "execution_count": 23, "id": "595ec598", "metadata": {}, "outputs": [], "source": [ "line" ] }, { "cell_type": "markdown", "id": "ae02c7d2", "metadata": {}, "source": [ "A function like this is called a **pure function** because it returns a value and has no **side effects**." ] }, { "cell_type": "markdown", "id": "567ae734", "metadata": {}, "source": [ "## Return values and conditionals\n", "\n", "If Python did not provide `abs`, we could write it like this." ] }, { "cell_type": "code", "execution_count": 24, "id": "236c59e6", "metadata": {}, "outputs": [], "source": [ "def absolute_value(x):\n", " if x < 0:\n", " return -x\n", " else:\n", " return x" ] }, { "cell_type": "markdown", "id": "ffd559b8", "metadata": {}, "source": [ "If `x` is negative, the first `return` statement returns `-x` and the function ends immediately.\n", "Otherwise, the second `return` statement returns `x` and the function ends.\n", "So this function is correct.\n", "\n", "However, if you put `return` statements in a conditional, you have to make sure that every possible path through the program hits a `return` statement.\n", "For example, here's an incorrect version of `absolute_value`." ] }, { "cell_type": "code", "execution_count": 25, "id": "2f60639c", "metadata": {}, "outputs": [], "source": [ "def absolute_value_wrong(x):\n", " if x < 0:\n", " return -x\n", " if x > 0:\n", " return x" ] }, { "cell_type": "markdown", "id": "da3280ae", "metadata": {}, "source": [ "Here's what happens if we call this function with `0` as an argument.\n", "" ] }, { "cell_type": "code", "execution_count": 26, "id": "c9dae6c8", "metadata": {}, "outputs": [], "source": [ "absolute_value_wrong(0)" ] }, { "cell_type": "markdown", "id": "5733f239", "metadata": {}, "source": [ "We get nothing! Here's the problem: when `x` is `0`, neither condition is true, and the function ends without hitting a `return` statement, which means that the return value is `None`, so Jupyter displays nothing.\n", "\n", "As another example, here's a version of `absolute_value` with an extra `return` statement at the end." ] }, { "cell_type": "code", "execution_count": 27, "id": "c8c4edee", "metadata": {}, "outputs": [], "source": [ "def absolute_value_extra_return(x):\n", " if x < 0:\n", " return -x\n", " else:\n", " return x\n", " \n", " return 'This is dead code'" ] }, { "cell_type": "markdown", "id": "cf5486fd", "metadata": {}, "source": [ "If `x` is negative, the first `return` statement runs and the function ends.\n", "Otherwise the second `return` statement runs and the function ends.\n", "Either way, we never get to the third `return` statement -- so it can never run.\n", "\n", "Code that can never run is called **dead code**.\n", "In general, dead code doesn't do any harm, but it often indicates a misunderstanding, and it might be confusing to someone trying to understand the program." ] }, { "cell_type": "markdown", "id": "68a6ae39", "metadata": { "tags": [] }, "source": [ "## Incremental development\n", "\n", "As you write larger functions, you might find yourself spending more\n", "time debugging.\n", "To deal with increasingly complex programs, you might want to try **incremental development**, which is a way of adding and testing only a small amount of code at a time.\n", "\n", "As an example, suppose you want to find the distance between two points represented by the coordinates $(x_1, y_1)$ and $(x_2, y_2)$.\n", "By the Pythagorean theorem, the distance is:\n", "\n", "$$\\mathrm{distance} = \\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$ \n", "\n", "The first step is to consider what a `distance` function should look like in Python -- that is, what are the inputs (parameters) and what is the output (return value)?\n", "\n", "For this function, the inputs are the coordinates of the points.\n", "The return value is the distance.\n", "Immediately you can write an outline of the function:" ] }, { "cell_type": "code", "execution_count": 28, "id": "bbcab1ed", "metadata": {}, "outputs": [], "source": [ "def distance(x1, y1, x2, y2):\n", " return 0.0" ] }, { "cell_type": "markdown", "id": "7b384fcf", "metadata": {}, "source": [ "This version doesn't compute distances yet -- it always returns zero.\n", "But it is a complete function with a return value, which means that you can test it before you make it more complicated.\n", "\n", "To test the new function, we'll call it with sample arguments:" ] }, { "cell_type": "code", "execution_count": 29, "id": "923d96db", "metadata": {}, "outputs": [], "source": [ "distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "13a98096", "metadata": {}, "source": [ "I chose these values so that the horizontal distance is `3` and the\n", "vertical distance is `4`.\n", "That way, the result is `5`, the hypotenuse of a `3-4-5` right triangle. When testing a function, it is useful to know the right answer.\n", "\n", "At this point we have confirmed that the function runs and returns a value, and we can start adding code to the body.\n", "A good next step is to find the differences `x2 - x1` and `y2 - y1`. \n", "Here's a version that stores those values in temporary variables and displays them." ] }, { "cell_type": "code", "execution_count": 30, "id": "9374cfe3", "metadata": {}, "outputs": [], "source": [ "def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " print('dx is', dx)\n", " print('dy is', dy)\n", " return 0.0" ] }, { "cell_type": "markdown", "id": "c342a3bd", "metadata": {}, "source": [ "If the function is working, it should display `dx is 3` and `dy is 4`.\n", "If so, we know that the function is getting the right arguments and\n", "performing the first computation correctly. If not, there are only a few\n", "lines to check." ] }, { "cell_type": "code", "execution_count": 31, "id": "405af839", "metadata": {}, "outputs": [], "source": [ "distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "9424eca9", "metadata": {}, "source": [ "Good so far. Next we compute the sum of squares of `dx` and `dy`:" ] }, { "cell_type": "code", "execution_count": 32, "id": "e52b3b04", "metadata": {}, "outputs": [], "source": [ "def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " print('dsquared is: ', dsquared)\n", " return 0.0" ] }, { "cell_type": "markdown", "id": "e28262f9", "metadata": {}, "source": [ "Again, we can run the function and check the output, which should be `25`. " ] }, { "cell_type": "code", "execution_count": 33, "id": "38eebbf3", "metadata": {}, "outputs": [], "source": [ "distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "c09f0ddc", "metadata": {}, "source": [ "Finally, we can use `math.sqrt` to compute the distance:" ] }, { "cell_type": "code", "execution_count": 34, "id": "b4536ea0", "metadata": {}, "outputs": [], "source": [ "def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " result = math.sqrt(dsquared)\n", " print(\"result is\", result)" ] }, { "cell_type": "markdown", "id": "f27902ac", "metadata": {}, "source": [ "And test it.\n", "" ] }, { "cell_type": "code", "execution_count": 35, "id": "325efb93", "metadata": {}, "outputs": [], "source": [ "distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "8ad2e626", "metadata": {}, "source": [ "The result is correct, but this version of the function displays the result rather than returning it, so the return value is `None`.\n", "\n", "We can fix that by replacing the `print` function with a `return` statement." ] }, { "cell_type": "code", "execution_count": 36, "id": "3cd982ce", "metadata": {}, "outputs": [], "source": [ "def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " result = math.sqrt(dsquared)\n", " return result" ] }, { "cell_type": "markdown", "id": "f3a13a14", "metadata": {}, "source": [ "This version of `distance` is a pure function.\n", "If we call it like this, only the result is displayed." ] }, { "cell_type": "code", "execution_count": 37, "id": "c734f5b2", "metadata": {}, "outputs": [], "source": [ "distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "7db8cf86", "metadata": {}, "source": [ "And if we assign the result to a variable, nothing is displayed." ] }, { "cell_type": "code", "execution_count": 38, "id": "094a242f", "metadata": {}, "outputs": [], "source": [ "d = distance(1, 2, 4, 6)" ] }, { "cell_type": "markdown", "id": "0c3b8829", "metadata": {}, "source": [ "The `print` statements we wrote are useful for debugging, but once the function is working, we can remove them. \n", "Code like that is called **scaffolding** because it is helpful for building the program but is not part of the final product.\n", "\n", "This example demonstrates incremental development.\n", "The key aspects of this process are:\n", "\n", "1. Start with a working program, make small changes, and test after every change.\n", "\n", "2. Use variables to hold intermediate values so you can display and check them.\n", "\n", "3. Once the program is working, remove the scaffolding.\n", "\n", "At any point, if there is an error, you should have a good idea where it is.\n", "Incremental development can save you a lot of debugging time." ] }, { "cell_type": "markdown", "id": "3dd7514f", "metadata": {}, "source": [ "## Boolean functions\n", "\n", "Functions can return the boolean values `True` and `False`, which is often convenient for encapsulating a complex test in a function.\n", "For example, `is_divisible` checks whether `x` is divisible by `y` with no remainder." ] }, { "cell_type": "code", "execution_count": 39, "id": "64207948", "metadata": {}, "outputs": [], "source": [ "def is_divisible(x, y):\n", " if x % y == 0:\n", " return True\n", " else:\n", " return False" ] }, { "cell_type": "markdown", "id": "f3a58afb", "metadata": {}, "source": [ "Here's how we use it." ] }, { "cell_type": "code", "execution_count": 40, "id": "c367cdae", "metadata": {}, "outputs": [], "source": [ "is_divisible(6, 4)" ] }, { "cell_type": "code", "execution_count": 41, "id": "837f4f95", "metadata": {}, "outputs": [], "source": [ "is_divisible(6, 3)" ] }, { "cell_type": "markdown", "id": "e9103ece", "metadata": {}, "source": [ "Inside the function, the result of the `==` operator is a boolean, so we can write the\n", "function more concisely by returning it directly." ] }, { "cell_type": "code", "execution_count": 42, "id": "e411354f", "metadata": {}, "outputs": [], "source": [ "def is_divisible(x, y):\n", " return x % y == 0" ] }, { "cell_type": "markdown", "id": "4d82dae5", "metadata": {}, "source": [ "Boolean functions are often used in conditional statements." ] }, { "cell_type": "code", "execution_count": 43, "id": "925e7d4f", "metadata": {}, "outputs": [], "source": [ "if is_divisible(6, 2):\n", " print('divisible')" ] }, { "cell_type": "markdown", "id": "9e232afc", "metadata": {}, "source": [ "It might be tempting to write something like this:" ] }, { "cell_type": "code", "execution_count": 44, "id": "62178e75", "metadata": {}, "outputs": [], "source": [ "if is_divisible(6, 2) == True:\n", " print('divisible')" ] }, { "cell_type": "markdown", "id": "ff9e5160", "metadata": {}, "source": [ "But the comparison is unnecessary." ] }, { "cell_type": "markdown", "id": "a932a966", "metadata": {}, "source": [ "## Recursion with return values\n", "\n", "Now that we can write functions with return values, we can write recursive functions with return values, and with that capability, we have passed an important threshold -- the subset of Python we have is now **Turing complete**, which means that we can perform any computation that can be described by an algorithm.\n", "\n", "To demonstrate recursion with return values, we'll evaluate a few recursively defined mathematical functions.\n", "A recursive definition is similar to a circular definition, in the sense that the definition refers to the thing being defined. A truly circular definition is not very useful:\n", "\n", "> vorpal: An adjective used to describe something that is vorpal.\n", "\n", "If you saw that definition in the dictionary, you might be annoyed. \n", "On the other hand, if you looked up the definition of the factorial function, denoted with the symbol $!$, you might get something like this: \n", "\n", "$$\\begin{aligned}\n", "0! &= 1 \\\\\n", "n! &= n~(n-1)!\n", "\\end{aligned}$$ \n", "\n", "This definition says that the factorial of $0$ is $1$, and the factorial of any other value, $n$, is $n$ multiplied by the factorial of $n-1$.\n", "\n", "If you can write a recursive definition of something, you can write a Python program to evaluate it. \n", "Following an incremental development process, we'll start with a function that take `n` as a parameter and always returns `0`." ] }, { "cell_type": "code", "execution_count": 45, "id": "23e37c79", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " return 0" ] }, { "cell_type": "markdown", "id": "ee1f63b8", "metadata": {}, "source": [ "Now let's add the first part of the definition -- if the argument happens to be `0`, all we have to do is return `1`:" ] }, { "cell_type": "code", "execution_count": 46, "id": "5ea57d9f", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " if n == 0:\n", " return 1\n", " else:\n", " return 0" ] }, { "cell_type": "markdown", "id": "4f2fd7c7", "metadata": {}, "source": [ "Now let's fill in the second part -- if `n` is not `0`, we have to make a recursive\n", "call to find the factorial of `n-1` and then multiply the result by `n`:" ] }, { "cell_type": "code", "execution_count": 47, "id": "b66e670b", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " if n == 0:\n", " return 1\n", " else:\n", " recurse = factorial(n-1)\n", " return n * recurse" ] }, { "cell_type": "markdown", "id": "da3d1595", "metadata": {}, "source": [ "The flow of execution for this program is similar to the flow of `countdown` in Chapter 5.\n", "If we call `factorial` with the value `3`:\n", "\n", "Since `3` is not `0`, we take the second branch and calculate the factorial\n", "of `n-1`\\...\n", "\n", "> Since `2` is not `0`, we take the second branch and calculate the\n", "> factorial of `n-1`\\...\n", ">\n", "> > Since `1` is not `0`, we take the second branch and calculate the\n", "> > factorial of `n-1`\\...\n", "> >\n", "> > > Since `0` equals `0`, we take the first branch and return `1` without\n", "> > > making any more recursive calls.\n", "> >\n", "> > The return value, `1`, is multiplied by `n`, which is `1`, and the\n", "> > result is returned.\n", ">\n", "> The return value, `1`, is multiplied by `n`, which is `2`, and the result\n", "> is returned.\n", "\n", "The return value `2` is multiplied by `n`, which is `3`, and the result,\n", "`6`, becomes the return value of the function call that started the whole\n", "process.\n", "\n", "The following figure shows the stack diagram for this sequence of function calls." ] }, { "cell_type": "code", "execution_count": 48, "id": "455f0457", "metadata": { "tags": [] }, "outputs": [], "source": [ "from diagram import Frame, Stack, make_binding\n", "\n", "main = Frame([], name='__main__', loc='left')\n", "frames = [main]\n", "\n", "ns = 3, 2, 1\n", "recurses = 2, 1, 1\n", "results = 6, 2, 1\n", "\n", "for n, recurse, result in zip(ns, recurses, results):\n", " binding1 = make_binding('n', n)\n", " binding2 = make_binding('recurse', recurse)\n", " frame = Frame([binding1, binding2], \n", " name='factorial', value=result,\n", " loc='left', dx=1.2)\n", " frames.append(frame)\n", " \n", "binding1 = make_binding('n', 0)\n", "frame = Frame([binding1], name='factorial', value=1, \n", " shim=1.2, loc='left', dx=1.4)\n", "frames.append(frame)\n", "\n", "stack = Stack(frames, dy=-0.45)" ] }, { "cell_type": "code", "execution_count": 49, "id": "a75ccd9b", "metadata": { "tags": [] }, "outputs": [], "source": [ "from diagram import diagram, adjust\n", "\n", "width, height, x, y = [2.74, 2.26, 0.73, 2.05]\n", "ax = diagram(width, height)\n", "bbox = stack.draw(ax, x, y)\n", "# adjust(x, y, bbox)" ] }, { "cell_type": "markdown", "id": "f924c539", "metadata": {}, "source": [ "The return values are shown being passed back up the stack.\n", "In each frame, the return value is the product of `n` and `recurse`.\n", "\n", "In the last frame, the local variable `recurse` does not exist because the branch that creates it does not run." ] }, { "cell_type": "markdown", "id": "acea9dc1", "metadata": {}, "source": [ "## Leap of faith\n", "\n", "Following the flow of execution is one way to read programs, but it can quickly become overwhelming. An alternative is what I call the \"leap of faith\". When you come to a function call, instead of following the flow of execution, you *assume* that the function works correctly and returns the right result.\n", "\n", "In fact, you are already practicing this leap of faith when you use built-in functions.\n", "When you call `abs` or `math.sqrt`, you don't examine the bodies of those functions -- you just assume that they work.\n", "\n", "The same is true when you call one of your own functions. For example, earlier we wrote a function called `is_divisible` that determines whether one number is divisible by another. Once we convince ourselves that this function is correct, we can use it without looking at the body again.\n", "\n", "The same is true of recursive programs.\n", "When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works and then ask yourself, \"Assuming that I can compute the factorial of $n-1$, can I compute the factorial of $n$?\"\n", "The recursive definition of factorial implies that you can, by multiplying by $n$.\n", "\n", "Of course, it's a bit strange to assume that the function works correctly when you haven't finished writing it, but that's why it's called a leap of faith!" ] }, { "cell_type": "markdown", "id": "ca2a2d76", "metadata": { "tags": [] }, "source": [ "## Fibonacci\n", "\n", "After `factorial`, the most common example of a recursive function is `fibonacci`, which has the following definition: \n", "\n", "$$\\begin{aligned}\n", "\\mathrm{fibonacci}(0) &= 0 \\\\\n", "\\mathrm{fibonacci}(1) &= 1 \\\\\n", "\\mathrm{fibonacci}(n) &= \\mathrm{fibonacci}(n-1) + \\mathrm{fibonacci}(n-2)\n", "\\end{aligned}$$ \n", "\n", "Translated into Python, it looks like this:" ] }, { "cell_type": "code", "execution_count": 50, "id": "cad75752", "metadata": {}, "outputs": [], "source": [ "def fibonacci(n):\n", " if n == 0:\n", " return 0\n", " elif n == 1:\n", " return 1\n", " else:\n", " return fibonacci(n-1) + fibonacci(n-2)" ] }, { "cell_type": "markdown", "id": "69d56a0b", "metadata": {}, "source": [ "If you try to follow the flow of execution here, even for small values of $n$, your head explodes.\n", "But according to the leap of faith, if you assume that the two recursive calls work correctly, you can be confident that the last `return` statement is correct.\n", "\n", "As an aside, this way of computing Fibonacci numbers is very inefficient.\n", "In [Chapter 10](section_memos) I'll explain why and suggest a way to improve it." ] }, { "cell_type": "markdown", "id": "26d9706b", "metadata": {}, "source": [ "## Checking types\n", "\n", "What happens if we call `factorial` and give it `1.5` as an argument?" ] }, { "cell_type": "code", "execution_count": 51, "id": "5e4b5f1d", "metadata": { "tags": [] }, "outputs": [], "source": [ "\n", "factorial(1.5)" ] }, { "cell_type": "markdown", "id": "0bec7ba4", "metadata": {}, "source": [ "It looks like an infinite recursion. How can that be? The function has base cases when `n == 1` or `n == 0`.\n", "But if `n` is not an integer, we can *miss* the base case and recurse forever.\n", "\n", "In this example, the initial value of `n` is `1.5`.\n", "In the first recursive call, the value of `n` is `0.5`.\n", "In the next, it is `-0.5`. \n", "From there, it gets smaller (more negative), but it will never be `0`.\n", "\n", "To avoid infinite recursion we can use the built-in function `isinstance` to check the type of the argument.\n", "Here's how we check whether a value is an integer." ] }, { "cell_type": "code", "execution_count": 52, "id": "3f607dff", "metadata": {}, "outputs": [], "source": [ "isinstance(3, int)" ] }, { "cell_type": "code", "execution_count": 53, "id": "ab638bfe", "metadata": {}, "outputs": [], "source": [ "isinstance(1.5, int)" ] }, { "cell_type": "markdown", "id": "b0017b42", "metadata": {}, "source": [ "Now here's a version of `factorial` with error-checking." ] }, { "cell_type": "code", "execution_count": 54, "id": "73aafac0", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " if not isinstance(n, int):\n", " print('factorial is only defined for integers.')\n", " return None\n", " elif n < 0:\n", " print('factorial is not defined for negative numbers.')\n", " return None\n", " elif n == 0:\n", " return 1\n", " else:\n", " return n * factorial(n-1)" ] }, { "cell_type": "markdown", "id": "0561e3f5", "metadata": {}, "source": [ "First it checks whether `n` is an integer.\n", "If not, it displays an error message and returns `None`.\n", "\n" ] }, { "cell_type": "code", "execution_count": 55, "id": "be881cb7", "metadata": {}, "outputs": [], "source": [ "factorial('crunchy frog')" ] }, { "cell_type": "markdown", "id": "10b00a39", "metadata": {}, "source": [ "Then it checks whether `n` is negative.\n", "If so, it displays an error message and returns `None.`" ] }, { "cell_type": "code", "execution_count": 56, "id": "fa83014f", "metadata": {}, "outputs": [], "source": [ "factorial(-2)" ] }, { "cell_type": "markdown", "id": "96aa1403", "metadata": {}, "source": [ "If we get past both checks, we know that `n` is a non-negative integer, so we can be confident the recursion will terminate.\n", "Checking the parameters of a function to make sure they have the correct types and values is called **input validation**." ] }, { "cell_type": "markdown", "id": "eb8a85a7", "metadata": { "tags": [] }, "source": [ "## Debugging\n", "\n", "Breaking a large program into smaller functions creates natural checkpoints for debugging.\n", "If a function is not working, there are three possibilities to consider:\n", "\n", "- There is something wrong with the arguments the function is getting -- that is, a precondition is violated.\n", "\n", "- There is something wrong with the function -- that is, a postcondition is violated.\n", "\n", "- The caller is doing something wrong with the return value.\n", "\n", "To rule out the first possibility, you can add a `print` statement at the beginning of the function that displays the values of the parameters (and maybe their types).\n", "Or you can write code that checks the preconditions explicitly.\n", "\n", "If the parameters look good, you can add a `print` statement before each `return` statement and display the return value.\n", "If possible, call the function with arguments that make it easy check the result. \n", "\n", "If the function seems to be working, look at the function call to make sure the return value is being used correctly -- or used at all!\n", "\n", "Adding `print` statements at the beginning and end of a function can help make the flow of execution more visible.\n", "For example, here is a version of `factorial` with print statements:" ] }, { "cell_type": "code", "execution_count": 57, "id": "1d50479e", "metadata": {}, "outputs": [], "source": [ "def factorial(n):\n", " space = ' ' * (4 * n)\n", " print(space, 'factorial', n)\n", " if n == 0:\n", " print(space, 'returning 1')\n", " return 1\n", " else:\n", " recurse = factorial(n-1)\n", " result = n * recurse\n", " print(space, 'returning', result)\n", " return result" ] }, { "cell_type": "markdown", "id": "0c044111", "metadata": {}, "source": [ "`space` is a string of space characters that controls the indentation of\n", "the output. Here is the result of `factorial(3)` :" ] }, { "cell_type": "code", "execution_count": 58, "id": "798db5c4", "metadata": {}, "outputs": [], "source": [ "factorial(3)" ] }, { "cell_type": "markdown", "id": "43b3e408", "metadata": {}, "source": [ "If you are confused about the flow of execution, this kind of output can be helpful.\n", "It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging." ] }, { "cell_type": "markdown", "id": "b7c3962f", "metadata": {}, "source": [ "## Glossary\n", "\n", "**return value:**\n", "The result of a function. If a function call is used as an expression, the return value is the value of the expression.\n", "\n", "**side effect:**\n", "Any effect a function has other than returning a value, such as displaying output or drawing on a canvas.\n", "\n", "**pure function:**\n", "A function that returns a value and has no side effects.\n", "\n", "\n", "**dead code:**\n", "Part of a program that can never run, often because it appears after a `return` statement.\n", "\n", "**incremental development:**\n", "A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.\n", "\n", "**scaffolding:**\n", " Code that is used during program development but is not part of the final version.\n", "\n", "**Turing complete:**\n", "A language, or subset of a language, is Turing complete if it can perform any computation that can be described by an algorithm.\n", "\n", "**input validation:**\n", "Checking the parameters of a function to make sure they have the correct types and values" ] }, { "cell_type": "markdown", "id": "0e0543e6", "metadata": {}, "source": [ "\n", "**See also:** the [full vocabulary glossary](https://python.porttack.com/alignment/ap-vocabulary-glossary.html) collects every term in this book, alphabetized, alongside the complete AP CSP exam vocabulary list.\n", "" ] }, { "cell_type": "markdown", "id": "ff7b1edf", "metadata": {}, "source": [ "## Exercises" ] }, { "cell_type": "code", "execution_count": 59, "id": "e0f15ca4", "metadata": { "tags": [] }, "outputs": [], "source": [ "# This cell tells Jupyter to provide detailed debugging information\n", "# when a runtime error occurs. Run it before working on the exercises.\n", "\n", "%xmode Verbose" ] }, { "cell_type": "markdown", "id": "fd23bb60", "metadata": {}, "source": [ "### Exercise\n", "\n", "Use incremental development to write a function called `hypot` that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments.\n", "\n", "Note: There's a function in the math module called `hypot` that does the same thing, but you should not use it for this exercise!\n", "\n", "Even if you can write the function correctly on the first try, start with a function that always returns `0` and practice making small changes, testing as you go.\n", "When you are done, the function should only return a value -- it should not display anything." ] }, { "cell_type": "code", "execution_count": 63, "id": "62267fa3", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 64, "id": "5f8fa829", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 65, "id": "3d129b03", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 66, "id": "030179b6", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 67, "id": "d737b468", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 68, "id": "77a74879", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 69, "id": "0521d267", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 70, "id": "468a31e9", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 71, "id": "abbe3ebf", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 72, "id": "651295e4", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "0a66d82a", "metadata": {}, "source": [ "### Exercise\n", "\n", "Write a boolean function, `is_between(x, y, z)`, that returns `True` if $x < y < z$ or if \n", "$z < y < x$, and`False` otherwise." ] }, { "cell_type": "code", "execution_count": 73, "id": "0a4ee482", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "c12f318d", "metadata": { "tags": [] }, "source": [ "You can use these examples to test your function." ] }, { "cell_type": "code", "execution_count": 74, "id": "956ed6d7", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_between(1, 2, 3) # should be True" ] }, { "cell_type": "code", "execution_count": 75, "id": "a994eaa6", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_between(3, 2, 1) # should be True" ] }, { "cell_type": "code", "execution_count": 76, "id": "4318028d", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_between(1, 3, 2) # should be False" ] }, { "cell_type": "code", "execution_count": 77, "id": "05208c8b", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_between(2, 3, 1) # should be False" ] }, { "cell_type": "markdown", "id": "57f06466", "metadata": {}, "source": [ "### Exercise\n", "\n", "The Ackermann function, $A(m, n)$, is defined:\n", "\n", "$$\\begin{aligned}\n", "A(m, n) = \\begin{cases} \n", " n+1 & \\mbox{if } m = 0 \\\\ \n", " A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ \n", "A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0.\n", "\\end{cases} \n", "\\end{aligned}$$ \n", "\n", "Write a function named `ackermann` that evaluates the Ackermann function.\n", "What happens if you call `ackermann(5, 5)`?" ] }, { "cell_type": "code", "execution_count": 78, "id": "7eb85c5c", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "85f7f614", "metadata": { "tags": [] }, "source": [ "You can use these examples to test your function." ] }, { "cell_type": "code", "execution_count": 79, "id": "687a3e5a", "metadata": { "tags": [] }, "outputs": [], "source": [ "ackermann(3, 2) # should be 29" ] }, { "cell_type": "code", "execution_count": 80, "id": "c49e9749", "metadata": { "tags": [] }, "outputs": [], "source": [ "ackermann(3, 3) # should be 61" ] }, { "cell_type": "code", "execution_count": 81, "id": "8497dec4", "metadata": { "tags": [] }, "outputs": [], "source": [ "ackermann(3, 4) # should be 125" ] }, { "cell_type": "markdown", "id": "4994ceae", "metadata": { "tags": [] }, "source": [ "If you call this function with values bigger than 4, you get a `RecursionError`." ] }, { "cell_type": "code", "execution_count": 82, "id": "76be4d15", "metadata": { "tags": [] }, "outputs": [], "source": [ "\n", "ackermann(5, 5)" ] }, { "cell_type": "markdown", "id": "b8af1586", "metadata": { "tags": [] }, "source": [ "To see why, add a print statement to the beginning of the function to display the values of the parameters, and then run the examples again." ] }, { "cell_type": "markdown", "id": "7c2ac0a4", "metadata": { "tags": [] }, "source": [ "### Exercise\n", "\n", "A number, $a$, is a power of $b$ if it is divisible by $b$ and $a/b$ is\n", "a power of $b$. Write a function called `is_power` that takes parameters\n", "`a` and `b` and returns `True` if `a` is a power of `b`. Note: you will\n", "have to think about the base case." ] }, { "cell_type": "code", "execution_count": 83, "id": "0bcba5fe", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "e93a0715", "metadata": { "tags": [] }, "source": [ "You can use these examples to test your function." ] }, { "cell_type": "code", "execution_count": 84, "id": "4b6656e6", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_power(65536, 2) # should be True" ] }, { "cell_type": "code", "execution_count": 85, "id": "36d9e92a", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_power(27, 3) # should be True" ] }, { "cell_type": "code", "execution_count": 86, "id": "1d944b42", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_power(24, 2) # should be False" ] }, { "cell_type": "code", "execution_count": 87, "id": "63ec57c9", "metadata": { "tags": [] }, "outputs": [], "source": [ "is_power(1, 17) # should be True" ] }, { "cell_type": "markdown", "id": "a33bbd07", "metadata": {}, "source": [ "### Exercise\n", "\n", "The greatest common divisor (GCD) of $a$ and $b$ is the largest number\n", "that divides both of them with no remainder.\n", "\n", "One way to find the GCD of two numbers is based on the observation that\n", "if $r$ is the remainder when $a$ is divided by $b$, then $gcd(a,\n", "b) = gcd(b, r)$. As a base case, we can use $gcd(a, 0) = a$.\n", "\n", "Write a function called `gcd` that takes parameters `a` and `b` and\n", "returns their greatest common divisor." ] }, { "cell_type": "code", "execution_count": 88, "id": "4e067bfb", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "efbebde9", "metadata": { "tags": [] }, "source": [ "You can use these examples to test your function." ] }, { "cell_type": "code", "execution_count": 89, "id": "2a7c1c21", "metadata": { "tags": [] }, "outputs": [], "source": [ "gcd(12, 8) # should be 4" ] }, { "cell_type": "code", "execution_count": 90, "id": "5df00229", "metadata": { "tags": [] }, "outputs": [], "source": [ "gcd(13, 17) # should be 1" ] }, { "cell_type": "code", "execution_count": null, "id": "8bec38b3", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06-extra-exercises-intro", "metadata": {}, "source": [ "\n", "## Homework\n", "\n", "Required work is four exercises: whichever of Exercise 1 or Exercise 2, plus Exercises 3-5, about 31 minutes total. Doing both 1 and 2 is fine, but the second one earns no additional credit. The time check below must be filled in. The extra credit at the end (`to_binary` and `collatz_steps`) is the only extra credit in this chapter. It's optional and never substitutes for a required exercise.\n", "\n", "Every function you write in this section needs a docstring, the same as chapter 4 on.\n", "\n", "Note: the exercises above (`hypot`, `is_between`, the Ackermann function, `is_power`, and `gcd`) are practice. They aren't graded. This is the graded homework.\n", "" ] }, { "cell_type": "markdown", "id": "ch06ex-hw01-heading", "metadata": {}, "source": [ "\n", "\n", "### Exercise 1: is_right_triangle (do 1 or 2)\n", "\n", "Write a function called `is_right_triangle` that takes three side lengths, `a`, `b`, and `c`, and returns `True` if they form a right triangle (the Pythagorean theorem holds for some pairing of the three sides as the two legs and the hypotenuse) and `False` otherwise. Don't assume the sides are given in any particular order.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw01-solution", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06ex-hw01-test-note", "metadata": {}, "source": [ "Test your function with the following cases." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw01-test1", "metadata": {}, "outputs": [], "source": [ "if is_right_triangle(3, 4, 5):\n", " print('right triangle')" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw01-test2", "metadata": {}, "outputs": [], "source": [ "is_right_triangle(4, 5, 3) # should be True" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw01-test3", "metadata": {}, "outputs": [], "source": [ "is_right_triangle(2, 3, 4) # should be False" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw01-test4", "metadata": {}, "outputs": [], "source": [ "is_right_triangle(0, 5, 5) # should be True" ] }, { "cell_type": "markdown", "id": "ch06ex-hw02-heading", "metadata": {}, "source": [ "\n", "\n", "### Exercise 2: can_ride (do 1 or 2)\n", "\n", "Write a function called `can_ride` that takes `height_inches` and `age` and returns `True` if the person may ride: at least 48 inches tall, or at least 42 inches tall and at least 8 years old. Otherwise it returns `False`.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw02-solution", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06ex-hw02-test-note", "metadata": {}, "source": [ "Test your function with the following cases." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw02-test1", "metadata": {}, "outputs": [], "source": [ "if can_ride(50, 5):\n", " print('can ride')" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw02-test2", "metadata": {}, "outputs": [], "source": [ "can_ride(44, 6) # should be False" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw02-test3", "metadata": {}, "outputs": [], "source": [ "can_ride(40, 10) # should be False" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw02-test4", "metadata": {}, "outputs": [], "source": [ "can_ride(36, 5) # should be False" ] }, { "cell_type": "markdown", "id": "ch06ex-hw03-heading", "metadata": {}, "source": [ "\n", "\n", "### Exercise 3: sum_to\n", "\n", "Write a recursive function called `sum_to` that takes a positive integer `n` and returns the sum of the integers from 1 to `n`. As a base case, `sum_to(0)` should return `0`.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw03-solution", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06ex-hw03-test-note", "metadata": {}, "source": [ "Test your function with the following cases." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw03-test1", "metadata": {}, "outputs": [], "source": [ "sum_to(0) # should be 0" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw03-test2", "metadata": {}, "outputs": [], "source": [ "sum_to(1) # should be 1" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw03-test3", "metadata": {}, "outputs": [], "source": [ "sum_to(5) # should be 15" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw03-test4", "metadata": {}, "outputs": [], "source": [ "sum_to(10) # should be 55" ] }, { "cell_type": "markdown", "id": "ch06ex-hw04-heading", "metadata": {}, "source": [ "\n", "\n", "### Exercise 4: debug grade_points\n", "\n", "Here's a function that's supposed to convert a letter grade into grade points.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw04-buggy-code", "metadata": {}, "outputs": [], "source": [ "def grade_points(letter):\n", " if letter == 'A':\n", " print(4.0)\n", " elif letter == 'B':\n", " print(3.0)\n", " elif letter == 'C':\n", " print(2.0)" ] }, { "cell_type": "markdown", "id": "ch06ex-hw04-run-note", "metadata": {}, "source": [ "Predict what `gpa` will be before you run the cell below." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw04-xmode", "metadata": {}, "outputs": [], "source": [ "%xmode Context" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw04-run-crash", "metadata": {}, "outputs": [], "source": [ "\n", "gpa = grade_points('A') * 3" ] }, { "cell_type": "markdown", "id": "ch06ex-hw04-answer-note", "metadata": {}, "source": [ "In the markdown cell below, explain what goes wrong and why. Then, in the code cell after that, write a corrected version of `grade_points` and test it with `'A'`, `'B'`, and `'C'`." ] }, { "cell_type": "markdown", "id": "ch06ex-hw04-answer-md", "metadata": {}, "source": [ "*Type your answer here.*" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06ex-hw04-answer-code", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06ex-hw05-heading", "metadata": {}, "source": [ "\n", "\n", "### Exercise 5: reflection\n", "\n", "This chapter's functions return values instead of printing them. Give one example from your own code (from this chapter or an earlier one) where returning a value would let you do something that printing would not.\n", "\n", "Answer in the markdown cell below, the same way you did in chap01 through chap05.\n", "" ] }, { "cell_type": "markdown", "id": "ch06ex-hw05-answer", "metadata": {}, "source": [ "*Type your answer here.*" ] }, { "cell_type": "markdown", "id": "ch06-timecheck-heading", "metadata": {}, "source": [ "\n", "\n", "### Time check\n", "\n", "This is graded on being filled in, not on the numbers. There's no right answer, and low numbers don't score better. If this chapter took you three hours, I need to know that. These are estimates: nobody expects you to have timed yourself, so a rough number is exactly what's wanted.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-timecheck-code", "metadata": {}, "outputs": [], "source": [ "# Fill this in before you submit. Rough estimates are fine, and low numbers\n", "# don't score better. Don't count time on the extra credit below.\n", "# chapter_minutes -> reading the chapter and its practice exercises\n", "# extra_exercises_minutes -> the five numbered exercises above\n", "# longest -> which exercise took longest, e.g. 1\n", "chapter_minutes = 0\n", "extra_exercises_minutes = 0\n", "longest = 0\n", "\n", "from working_in_python import time_check\n", "time_check(chapter_minutes, extra_exercises_minutes, longest)" ] }, { "cell_type": "markdown", "id": "ch06-extra-credit-intro", "metadata": {}, "source": [ "\n", "## Extra credit: to_binary and collatz_steps\n", "\n", "Both of these are worth 0.25 points each, for 0.5 points total. Do one or both. Either is open to you once you've finished the five required exercises above; neither substitutes for any of them.\n", "" ] }, { "cell_type": "markdown", "id": "ch06-to-binary-heading", "metadata": {}, "source": [ "\n", "\n", "### to_binary (extra credit)\n", "\n", "Write a recursive function called `to_binary` that takes a non-negative integer `n` and returns its binary representation as a string of ones and zeros. This is how a number actually lives in memory, one bit at a time.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-to-binary-solution", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06-to-binary-test-note", "metadata": {}, "source": [ "Test your function with the following cases." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-to-binary-test1", "metadata": {}, "outputs": [], "source": [ "to_binary(0) # should be '0'" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-to-binary-test2", "metadata": {}, "outputs": [], "source": [ "to_binary(1) # should be '1'" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-to-binary-test3", "metadata": {}, "outputs": [], "source": [ "to_binary(10) # should be '1010'" ] }, { "cell_type": "markdown", "id": "ch06-collatz-steps-heading", "metadata": {}, "source": [ "\n", "\n", "### collatz_steps (extra credit)\n", "\n", "Write a recursive function called `collatz_steps` that takes a positive integer `n` and returns the number of steps it takes to reach `1` under the Collatz process: if `n` is even, the next number is `n // 2`; if `n` is odd, the next number is `3 * n + 1`. `collatz_steps(1)` should return `0`.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-collatz-steps-solution", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "ch06-collatz-steps-test-note", "metadata": {}, "source": [ "Test your function with the following cases." ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-collatz-steps-test1", "metadata": {}, "outputs": [], "source": [ "collatz_steps(1) # should be 0" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-collatz-steps-test2", "metadata": {}, "outputs": [], "source": [ "collatz_steps(6) # should be 8" ] }, { "cell_type": "markdown", "id": "ch06-copy-heading", "metadata": {}, "source": [ "\n", "### Finished? Copy your work\n", "\n", "This isn't part of Exercise 5. It's a tool. Run the cell below to copy this notebook (including anything you've run) so you can paste it into a document.\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ch06-copy-button", "metadata": {}, "outputs": [], "source": [ "working_in_python.show_copy_notebook_button()" ] }, { "cell_type": "markdown", "id": "a7f4edf8", "metadata": { "tags": [] }, "source": [ "\n", "---\n", "\n", "**Working in Python** — modified by Eric Brown for a high school Computer Science Principles class. Source and modifications: [github.com/porttack/working-in-python](https://github.com/porttack/working-in-python)\n", "\n", "---\n", "\n", "\n", "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", "Code license: [MIT License](https://mit-license.org/)\n", "\n", "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n", "\n", "\n", "---\n", "\n", "## Standards alignment\n", "\n", "**AP CSP:** [3.9 Developing Algorithms](https://python.porttack.com/alignment/apcsp-standards-reference.html#T-3.9) and [3.12 Calling Procedures](https://python.porttack.com/alignment/apcsp-standards-reference.html#T-3.12) (Big Idea 3, 30–35% of the exam). Also [1.4 Identifying and Correcting Errors](https://python.porttack.com/alignment/apcsp-standards-reference.html#T-1.4) (Big Idea 1, 10–13%), headers only.\n", "**California 9-12:** [9-12.AP.14](https://python.porttack.com/alignment/ca-cs-standards-reference.html#S-9-12.AP.14)\n", "**CSTA 2026:** [HS-PRO-RD-17](https://python.porttack.com/alignment/csta2026-standards-reference.html#T-HS-PRO-RD-17), headers only — no CSTA HS standard names recursion or abstraction directly.\n", "**CA CTE (ICT):** [C4.9](https://python.porttack.com/alignment/ca-ict-anchor-standards-reference.html#T-C4.9) (Pathway C) and [5.10](https://python.porttack.com/alignment/ca-ict-anchor-standards-reference.html#T-5.10) (Anchor Standard 5, Problem Solving). Also [C4.4](https://python.porttack.com/alignment/ca-ict-anchor-standards-reference.html#T-C4.4) and [C5.6](https://python.porttack.com/alignment/ca-ict-anchor-standards-reference.html#T-C5.6), headers only.\n", "\n", "Return values let a function call nest inside an expression, which is 3.9 and 3.12 built out with five successive versions of `distance`. `factorial` and `fibonacci` calling themselves is exactly CTE's \"function that calls itself,\" completing the same construct California's AP.14 asks for — thin on the iterative side, since this book has no `while` loop to compare recursion against. The leap of faith, trusting a function's return value without re-checking its body, is this book's clearest statement yet of CTE's layers-of-abstraction standard.\n", "" ] } ], "metadata": { "celltoolbar": "Tags", "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.11" } }, "nbformat": 4, "nbformat_minor": 5 }