Think Python/Fruitful functions

Return values
Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to a variable or use as part of an expression.

All of the functions we have written so far are void; they print something or move turtles around, but their return value is None.

In this chapter, we are (finally) going to write fruitful functions. The first example is area, which returns the area of a circle with the given radius:

We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: &#X201C;Return immediately from this function and use the following expression as a return value.&#X201D; The expression can be arbitrarily complicated, so we could have written this function more concisely:

On the other hand, temporary variables like temp often make debugging easier.

Sometimes it is useful to have multiple return statements, one in each branch of a conditional:

Since these return statements are in an alternative conditional, only one will be executed.

As soon as a return statement executes, the function terminates without executing any subsequent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.

In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example:

This function is incorrect because if <TT>x</TT> happens to be 0, neither condition is true, and the function ends without hitting a <TT>return</TT> statement. If the flow of execution gets to the end of a function, the return value is <TT>None</TT>, which is not the absolute value of 0.

By the way, Python provides a built-in function called <TT>abs</TT> that computes absolute values.

Exercise 1
Write a '<TT>compare</TT>' function that returns '<TT>1</TT>' if '<TT>x > y</TT>', '<TT>0</TT>' if '<TT>x == y</TT>', and '<TT>-1</TT>' if '<TT>x &lt; y</TT>'.

Incremental development
As you write larger functions, you might find yourself spending more time debugging.

To deal with increasingly complex programs, you might want to try a process called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time.

As an example, suppose you want to find the distance between two points, given by the coordinates (<I>x</I><SUB>1</SUB>, <I>y</I><SUB>1</SUB>) and (<I>x</I><SUB>2</SUB>, <I>y</I><SUB>2</SUB>). By the Pythagorean theorem, the distance is:

$$ \text{distance} = \sqrt{ (x_2 - x_1)^2 + (y_2 - y_1)^2} $$

The first step is to consider what a <TT>distance</TT> function should look like in Python. In other words, what are the inputs (parameters) and what is the output (return value)?

In this case, the inputs are two points, which you can represent using four numbers. The return value is the distance, which is a floating-point value.

Already you can write an outline of the function:

Obviously, this version doesn't compute distances; it always returns zero. But it is syntactically correct, and it runs, which means that you can test it before you make it more complicated.

To test the new function, call it with sample arguments:

I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle). When testing a function, it is useful to know the right answer.

At this point we have confirmed that the function is syntactically correct, and we can start adding code to the body. A reasonable next step is to find the differences <I>x</I><SUB>2</SUB> &#X2212; <I>x</I><SUB>1</SUB> and <I>y</I><SUB>2</SUB> &#X2212; <I>y</I><SUB>1</SUB>. The next version stores those values in temporary variables and prints them.

If the function is working, it should display  and <TT>&#X2019;dy is 4&#X2019;</TT>. If so, we know that the function is getting the right arguments and performing the first computation correctly. If not, there are only a few lines to check.

Next we compute the sum of squares of <TT>dx</TT> and <TT>dy</TT>:

Again, you would run the program at this stage and check the output (which should be 25). Finally, you can use <TT>math.sqrt</TT> to compute and return the result:

If that works correctly, you are done. Otherwise, you might want to print the value of <TT>result</TT> before the return statement.

The final version of the function doesn&#X2019;t display anything when it runs; it only returns a value. The <TT>print</TT> statements we wrote are useful for debugging, but once you get the function working, you should remove them. Code like that is called scaffolding because it is helpful for building the program but is not part of the final product.

When you start out, you should add only a line or two of code at a time. As you gain more experience, you might find yourself writing and debugging bigger chunks. Either way, incremental development can save you a lot of debugging time.

The key aspects of the process are:


 * Start with a working program and make small incremental changes. At any point, if there is an error, you should have a good idea where it is.
 * Use temporary variables to hold intermediate values so you can display and check them.
 * Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.

Exercise 2
''Use incremental development to write a function called '<TT>hypotenuse</TT>' that returns the length of the hypotenuse of a right triangle given the lengths of the two legs as arguments. Record each stage of the development process as you go.''

Composition
As you should expect by now, you can call one function from within another. This ability is called composition.

As an example, we&#X2019;ll write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle.

Assume that the center point is stored in the variables <TT>xc</TT> and <TT>yc</TT>, and the perimeter point is in <TT>xp</TT> and <TT>yp</TT>. The first step is to find the radius of the circle, which is the distance between the two points. We just wrote a function, <TT>distance</TT>, that does that:

The next step is to find the area of a circle with that radius; we just wrote that, too:

Encapsulating these steps in a function, we get:

The temporary variables <TT>radius</TT> and <TT>result</TT> are useful for development and debugging, but once the program is working, we can make it more concise by composing the function calls:

Boolean functions
Functions can return booleans, which is often convenient for hiding complicated tests inside functions. For example: It is common to give boolean functions names that sound like yes/no questions;  returns either <TT>True</TT> or <TT>False</TT> to indicate whether <TT>x</TT> is divisible by <TT>y</TT>.

Here is an example: The result of the <TT>==</TT> operator is a boolean, so we can write the function more concisely by returning it directly: Boolean functions are often used in conditional statements:

It might be tempting to write something like: But the extra comparison is unnecessary.

<DIV CLASS="theorem"> Exercise&#XA0;3&#XA0;&#XA0;Write a function   that returns '<TT>True</TT>' if '<I>x</I> &#X2264; <I>y</I> &#X2264; <I>z</I>' or '<TT>False</TT>' otherwise. </DIV>

More recursion
We have only covered a small subset of Python, but you might be interested to know that this subset is a complete programming language, which means that anything that can be computed can be expressed in this language. Any program ever written could be rewritten using only the language features you have learned so far (actually, you would need a few commands to control devices like the keyboard, mouse, disks, etc., but that&#X2019;s all).

Proving that claim is a nontrivial exercise first accomplished by Alan Turing, one of the first computer scientists (some would argue that he was a mathematician, but a lot of early computer scientists started as mathematicians). Accordingly, it is known as the Turing Thesis. For a more complete (and accurate) discussion of the Turing Thesis, I recommend Michael Sipser&#X2019;s book Introduction to the Theory of Computation.

To give you an idea of what you can do with the tools you have learned so far, we&#X2019;ll evaluate a few recursively defined mathematical functions. A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is not very useful: <DL CLASS="description"><DT CLASS="dt-description">frabjuous:</DT><DD CLASS="dd-description"> An adjective used to describe something that is frabjuous.</DD></DL>

If you saw that definition in the dictionary, you might be annoyed. On the other hand, if you looked up the definition of the factorial function, denoted with the symbol !, you might get something like this: </TD></TR> </TABLE> This definition says that the factorial of 0 is 1, and the factorial of any other value, <I>n</I>, is <I>n</I> multiplied by the factorial of <I>n</I>&#X2212;1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6.

If you can write a recursive definition of something, you can usually write a Python program to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that <TT>factorial</TT> takes an integer: If the argument happens to be 0, all we have to do is return 1: Otherwise, and this is the interesting part, we have to make a recursive call to find the factorial of <I>n</I>&#X2212;1 and then multiply it by <I>n</I>: The flow of execution for this program is similar to the flow of <TT>countdown</TT> in Section&#XA0;5.8. If we call <TT>factorial</TT> with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of <TT>n-1</TT>... <BLOCKQUOTE CLASS="quote"> Since 2 is not 0, we take the second branch and calculate the factorial of <TT>n-1</TT>...<BLOCKQUOTE CLASS="quote"> Since 1 is not 0, we take the second branch and calculate the factorial of <TT>n-1</TT>...<BLOCKQUOTE CLASS="quote"> Since 0 is 0, we take the first branch and return 1 without making any more recursive calls. </BLOCKQUOTE> The return value (1) is multiplied by <I>n</I>, which is 1, and the result is returned.

</BLOCKQUOTE> The return value (1) is multiplied by <I>n</I>, which is 2, and the result is returned.

</BLOCKQUOTE> The return value (2) is multiplied by <I>n</I>, which is 3, and the result, 6, becomes the return value of the function call that started the whole process.

Here is what the stack diagram looks like for this sequence of function calls:

<BR>

<DIV CLASS="center"><IMG SRC="book009.png"></DIV>

<BR>

The return values are shown being passed back up the stack. In each frame, the return value is the value of <TT>result</TT>, which is the product of <TT>n</TT> and <TT>recurse</TT>.

In the last frame, the local variables <TT>recurse</TT> and <TT>result</TT> do not exist, because the branch that creates them does not execute.

Leap of faith
Following the flow of execution is one way to read programs, but it can quickly become labyrinthine. An alternative is what I call the &#X201C;leap of faith.&#X201D; 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.

In fact, you are already practicing this leap of faith when you use built-in functions. When you call <TT>math.cos</TT> or <TT>math.exp</TT>, you don&#X2019;t examine the bodies of those functions. You just assume that they work because the people who wrote the built-in functions were good programmers.

The same is true when you call one of your own functions. For example, in Section&#XA0;6.4, we wrote a function called that determines whether one number is divisible by another. Once we have convinced ourselves that this function is correct&#X2014;by examining the code and testing&#X2014;we can use the function without looking at the body again.

The same is true of recursive programs. When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works (yields the correct result) and then ask yourself, &#X201C;Assuming that I can find the factorial of <I>n</I>&#X2212;1, can I compute the factorial of <I>n</I>?&#X201D; In this case, it is clear that you can, by multiplying by <I>n</I>.

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!

One more example
After <TT>factorial</TT>, the most common example of a recursively defined mathematical function is <TT>fibonacci</TT>, which has the following definition : </TD></TR> </TABLE>

Translated into Python, it looks like this: If you try to follow the flow of execution here, even for fairly small values of <I>n</I>, your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together.

Checking types
What happens if we call <TT>factorial</TT> and give it 1.5 as an argument?

It looks like an infinite recursion. But how can that be? There is a base case&#X2014;when <TT>n == 0</TT>. But if <TT>n</TT> is not an integer, we can miss the base case and recurse forever.

In the first recursive call, the value of <TT>n</TT> is 0.5. In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0.

We have two choices. We can try to generalize the <TT>factorial</TT> function to work with floating-point numbers, or we can make <TT>factorial</TT> check the type of its argument. The first option is called the gamma function and it&#X2019;s a little beyond the scope of this book. So we&#X2019;ll go for the second.

We can use the built-in function <TT>isinstance</TT> to verify the type of the argument. While we&#X2019;re at it, we can also make sure the argument is positive:

The first base case handles nonintegers; the second catches negative integers. In both cases, the program prints an error message and returns <TT>None</TT> to indicate that something went wrong: If we get past both checks, then we know that <I>n</I> is a positive integer, and we can prove that the recursion terminates.

This program demonstrates a pattern sometimes called a guardian. The first two conditionals act as guardians, protecting the code that follows from values that might cause an error. The guardians make it possible to prove the correctness of the code.

Debugging
Breaking a large program into smaller functions creates natural checkpoints for debugging. If a function is not working, there are three possibilities to consider:

is getting; a precondition is violated.
 * There is something wrong with the arguments the function

is violated.
 * There is something wrong with the function; a postcondition

way it is being used.
 * There is something wrong with the return value or the

To rule out the first possibility, you can add a <TT>print</TT> statement at the beginning of the function and display the values of the parameters (and maybe their types). Or you can write code that checks the preconditions explicitly.

If the parameters look good, add a <TT>print</TT> statement before each <TT>return</TT> statement that displays the return value. If possible, check the result by hand. Consider calling the function with values that make it easy to check the result (as in Section&#XA0;6.2).

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!).

Adding print statements at the beginning and end of a function can help make the flow of execution more visible. For example, here is a version of <TT>factorial</TT> with print statements: <TT>space</TT> is a string of space characters that controls the indentation of the output. Here is the result of <TT>factorial(5)</TT> : If you are confused about the flow of execution, this kind of output can be helpful. It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging.

Glossary
<DL CLASS="description"><DT CLASS="dt-description">temporary variable:</DT><DD CLASS="dd-description"> A variable used to store an intermediate value in a complex calculation.

</DD><DT CLASS="dt-description">dead code:</DT><DD CLASS="dd-description"> Part of a program that can never be executed, often because it appears after a <TT>return</TT> statement. </DD><DT CLASS="dt-description"><TT>None</TT>:</DT><DD CLASS="dd-description"> A special value returned by functions that have no return statement or a return statement without an argument.

</DD><DT CLASS="dt-description">incremental development:</DT><DD CLASS="dd-description"> A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time. </DD><DT CLASS="dt-description">scaffolding:</DT><DD CLASS="dd-description"> Code that is used during program development but is not part of the final version. </DD><DT CLASS="dt-description">guardian:</DT><DD CLASS="dd-description"> A programming pattern that uses a conditional statement to check for and handle circumstances that might cause an error.

</DD></DL>

Exercise 4
''Draw a stack diagram for the following program. What does the program print?''

Exercise 5
The Ackermann function, '<I>A</I>(<I>m</I>, <I>n</I>)' is defined :

''Write a function named '<TT>ack</TT>' that evaluates Ackerman&#X2019;s function. Use your function to evaluate '<TT>ack(3, 4)</TT>', which should be 125. What happens for larger values of '<TT>m</TT>' and '<TT>n</TT>'?''

Exercise 6
''A palindrome is a word that is spelled the same backward and forward, like &#X201C;noon&#X201D; and &#X201C;redivider&#X201D;. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome.''

The following are functions that take a string argument and return the first, last, and middle letters:

We&#X2019;ll see how they work in Chapter&#XA0;'8'.


 * Type these functions into a file named '<TT>palindrome.py</TT>' and test them out. What happens if you call '<TT>middle</TT>' with a string with two letters? One letter? What about the empty string, which is written and contains no letters?


 * Write a function called   that takes a string argument and returns '<TT>True</TT>' if it is a palindrome and '<TT>False</TT>' otherwise. Remember that you can use the built-in function '<TT>len</TT>' to check the length of a string.

Exercise 7
A number, <I>a</I>, is a power of <I>b</I> if it is divisible by <I>b</I> and <I>a</I>/<I>b</I> is a power of <I>b</I>. Write a function called  that takes parameters <TT>a</TT> and <TT>b</TT> and returns <TT>True</TT> if <TT>a</TT> is a power of <TT>b</TT>.

Exercise 8
The greatest common divisor (GCD) of '<I>a</I>' and '<I>b</I>' is the largest number that divides both of them with no remainder .

''One way to find the GCD of two numbers is Euclid&#X2019;s algorithm, which is based on the observation that if '<I>r</I>' is the remainder when '<I>a</I>' is divided by '<I>b</I>', then '<I>gcd</I>(<I>a</I>, <I>b</I>) = <I>gcd</I>(<I>b</I>, <I>r</I>)'. As a base case, we can consider '<I>gcd</I>(<I>a</I>, 0) = <I>a</I>'.''

Write a function called  '' that takes parameters '<TT>a</TT>' and '<TT>b</TT>' and returns their greatest common divisor. If you need help, see '<TT>wikipedia.org/wiki/Euclidean_algorithm</TT>'.''