Jump to content

Archive:Think Python/Conditional and recursion

From IdeaWazaWiki
Revision as of 22:43, 15 September 2008 by wikademia>Whiteknight (Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"

           "http://www.w3.org/TR/REC-html40/loose.dtd">

<HTML> <HEAD>

<META http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="book.css"> <TITLE>Conditionals and recursion</TITLE> </HEAD> <BODY > <A HREF="book005.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book007.html"><IMG SRC="next_motif.gif" ALT="Next"></A>


<A NAME="htoc57">Chapter 5</A>  Conditionals and recursion

<A NAME="toc51"></A><A NAME="htoc58">5.1</A>  Modulus operator

<A NAME="@default342"></A> <A NAME="@default343"></A>

The modulus operator works on integers and yields the remainder

when the first operand is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same

as for other operators:

<FONT COLOR=blue><FONT SIZE=4>>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
</FONT></FONT>

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. For

example, you can check whether one number is divisible by another—if

x % y is zero, then x is divisible by y.

<A NAME="@default344"></A>

Also, you can extract the right-most digit

or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100

yields the last two digits.

<A NAME="toc52"></A><A NAME="htoc59">5.2</A>  Boolean expressions

<A NAME="@default345"></A> <A NAME="@default346"></A> <A NAME="@default347"></A>

<A NAME="@default348"></A>

A boolean expression is an expression that is either true

or false. The following examples use the operator ==, which compares two operands and produces

True if they are equal and False otherwise:

<FONT COLOR=blue><FONT SIZE=4>>>> 5 == 5
True
>>> 5 == 6
False
</FONT></FONT>

True and False are special values that belong to the type bool; they are not strings:

<A NAME="@default349"></A>

<A NAME="@default350"></A> <A NAME="@default351"></A> <A NAME="@default352"></A> <A NAME="@default353"></A>

<A NAME="@default354"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
</FONT></FONT>

The == operator is one of the comparison operators; the others are:

<FONT COLOR=blue><FONT SIZE=4>      x != y               # x is not equal to y
      x > y                # x is greater than y
      x < y                # x is less than y
      x >= y               # x is greater than or equal to y
      x <= y               # x is less than or equal to y
</FONT></FONT>

Although these operations are probably familiar to you, the Python

symbols are different from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a comparison operator. There is no such thing as

=< or =>.

<A NAME="@default355"></A> <A NAME="@default356"></A>

<A NAME="toc53"></A><A NAME="htoc60">5.3</A>  Logical operators

<A NAME="@default357"></A>

<A NAME="@default358"></A>

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is

similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0

and less than 10.

<A NAME="@default359"></A>

<A NAME="@default360"></A> <A NAME="@default361"></A> <A NAME="@default362"></A> <A NAME="@default363"></A>

<A NAME="@default364"></A>

n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean

expression, so not (x > y) is true if x > y is false,

that is, if x is less than or equal to y.

Strictly speaking, the operands of the logical operators should be

boolean expressions, but Python is not very strict.

Any nonzero number is interpreted as “true.”

<FONT COLOR=blue><FONT SIZE=4>>>> 17 and True
True
</FONT></FONT>

This flexibility can be useful, but there are some subtleties to

it that might be confusing. You might want to avoid it (unless

you know what you are doing).

<A NAME="toc54"></A><A NAME="htoc61">5.4</A>  Conditional execution

<A NAME="conditional execution"></A>

<A NAME="@default365"></A>

<A NAME="@default366"></A> <A NAME="@default367"></A> <A NAME="@default368"></A>

<A NAME="@default369"></A>

In order to write useful programs, we almost always need the ability

to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The

simplest form is the if statement:

<FONT COLOR=blue><FONT SIZE=4>if x > 0:
    print 'x is positive'
</FONT></FONT>

The boolean expression after the if statement is

called the condition. If it is true, then the indented

statement gets executed. If not, nothing happens.

<A NAME="@default370"></A>

<A NAME="@default371"></A>

<A NAME="@default372"></A>

if statements have the same structure as function definitions:

a header followed by an indented block. Statements like this are

called compound statements.

There is no limit on the number of statements that can appear in

the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that

case, you can use the pass statement, which does nothing.

<A NAME="@default373"></A> <A NAME="@default374"></A>

<FONT COLOR=blue><FONT SIZE=4>if x < 0:
    pass          # need to handle negative values!
</FONT></FONT>

<A NAME="toc55"></A><A NAME="htoc62">5.5</A>  Alternative execution

<A NAME="alternative execution"></A>

<A NAME="@default375"></A>

<A NAME="@default376"></A>

<A NAME="@default377"></A>

A second form of the if statement is alternative execution,

in which there are two possibilities and the condition determines

which one gets executed. The syntax looks like this:

<FONT COLOR=blue><FONT SIZE=4>if x%2 == 0:
    print 'x is even'
else:
    print 'x is odd'
</FONT></FONT>

If the remainder when x is divided by 2 is 0, then we

know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called

branches, because they are branches in the flow of execution.

<A NAME="@default378"></A>

<A NAME="toc56"></A><A NAME="htoc63">5.6</A>  Chained conditionals

<A NAME="@default379"></A>

<A NAME="@default380"></A>

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

<FONT COLOR=blue><FONT SIZE=4>if x < y:
    print 'x is less than y'
elif x > y:
    print 'x is greater than y'
else:
    print 'x and y are equal'
</FONT></FONT>

elif is an abbreviation of “else if.” Again, exactly one

branch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to be

at the end, but there doesn’t have to be one.

<A NAME="@default381"></A> <A NAME="@default382"></A>

<FONT COLOR=blue><FONT SIZE=4>if choice == 'a':
    draw_a()
elif choice == 'b':
    draw_b()
elif choice == 'c':
    draw_c()
</FONT></FONT>

Each condition is checked in order. If the first is false,

the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the

first true branch executes.

<A NAME="toc57"></A><A NAME="htoc64">5.7</A>  Nested conditionals

<A NAME="@default383"></A>

<A NAME="@default384"></A>

One conditional can also be nested within another. We could have written the trichotomy example like this:

<FONT COLOR=blue><FONT SIZE=4>if x == y:
    print 'x and y are equal'
else:
    if x < y:
        print 'x is less than y'
    else:
        print 'x is greater than y'
</FONT></FONT>

The outer conditional contains two branches. The

first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements,

although they could have been conditional statements as well.

Although the indentation of the statements makes the structure

apparent, nested conditionals become difficult to read very

quickly. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional

statements. For example, we can rewrite the following code using a

single conditional:

<FONT COLOR=blue><FONT SIZE=4>if 0 < x:
    if x < 10:
        print 'x is a positive single-digit number.'
</FONT></FONT>

The print statement is executed only if we make it past both conditionals, so we can get the same effect with the and operator:

<FONT COLOR=blue><FONT SIZE=4>if 0 < x and x < 10:
    print 'x is a positive single-digit number.'
</FONT></FONT>

<A NAME="toc58"></A><A NAME="htoc65">5.8</A>  Recursion

<A NAME="recursion"></A>

<A NAME="@default385"></A>

It is legal for one function to call another;

it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do.

For example, look at the following function:

<FONT COLOR=blue><FONT SIZE=4>def countdown(n):
    if n <= 0:
        print 'Blastoff!'
    else:
        print n
        countdown(n-1)
</FONT></FONT>

If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n and then calls a function named countdown—itself—passing n-1 as an argument.

What happens if we call this function like this?

<FONT COLOR=blue><FONT SIZE=4>>>> countdown(3)
</FONT></FONT>

The execution of countdown begins with n=3, and since n is greater than 0, it outputs the value 3, and then calls itself...

The execution of countdown begins with n=2, and since

n is greater than 0, it outputs the value 2, and then calls itself...

The execution of countdown begins with n=1, and since

n is greater than 0, it outputs the value 1, and then calls itself...

The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the word, “Blastoff!” and then returns.

The countdown that got n=1 returns.

The countdown that got n=2 returns.

The countdown that got n=3 returns.

And then you’re back in __main__. So, the total output looks like this:

<FONT COLOR=blue><FONT SIZE=4>3
2
1
Blastoff!
</FONT></FONT>

A function that calls itself is recursive; the process is called recursion.

<A NAME="@default386"></A> <A NAME="@default387"></A>

As another example, we can write a function that prints a string n times.

<FONT COLOR=blue><FONT SIZE=4>def print_n(s, n):
    if n <= 0:
        return
    print s
    print_n(s, n-1)
</FONT></FONT>

If n <= 0 the return statement exits the function. The

flow of execution immediately returns to the caller, and the remaining

lines of the function are not executed.

<A NAME="@default388"></A> <A NAME="@default389"></A>

The rest of the function is similar to countdown: if n is

greater than 0, it displays s and then calls itself to display s n−1 additional times. So the number of lines of output is 1 + (n - 1), which adds up to

n.

For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write

with a for loop and easy to write with recursion, so it is

good to start early.

<A NAME="toc59"></A><A NAME="htoc66">5.9</A>  Stack diagrams for recursive functions

<A NAME="@default390"></A> <A NAME="@default391"></A>

<A NAME="@default392"></A>

In Section <A HREF="book004.html#stackdiagram">3.10</A>, we used a stack diagram to represent

the state of a program during a function call. The same kind of

diagram can help interpret a recursive function.

Every time a function gets called, Python creates a new function

frame, which contains the function’s local variables and parameters. For a recursive function, there might be more than one frame on the

stack at the same time.

This figure shows a stack diagram for countdown called with n = 3:

<IMG SRC="book007.png">

As usual, the top of the stack is the frame for __main__.

It is empty because we did not create any variables in

__main__ or pass any arguments to it.

<A NAME="@default393"></A> <A NAME="@default394"></A>

The four countdown frames have different values for the

parameter n. The bottom of the stack, where n=0, is called the base case. It does not make a recursive call, so

there are no more frames.

Draw a stack diagram for print_n called with s = 'Hello' and n=2.

Write a function called do_n that takes a function object and a number, n as arguments, and that calls the given function n times.

<A NAME="toc60"></A><A NAME="htoc67">5.10</A>  Infinite recursion

<A NAME="@default395"></A> <A NAME="@default396"></A> <A NAME="@default397"></A> <A NAME="@default398"></A>

<A NAME="@default399"></A>

If a recursion never reaches a base case, it goes on making

recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not

a good idea. Here is a minimal program with an infinite recursion:

<FONT COLOR=blue><FONT SIZE=4>def recurse():
    recurse()
</FONT></FONT>

In most programming environments, a program with infinite recursion

does not really run forever. Python reports an error

message when the maximum recursion depth is reached:

<A NAME="@default400"></A> <A NAME="@default401"></A>

<FONT COLOR=blue><FONT SIZE=4>  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
                  .   
                  .
                  .
  File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded
</FONT></FONT>

This traceback is a little bigger than the one we saw in the

previous chapter. When the error occurs, there are 1000

recurse frames on the stack!

<A NAME="toc61"></A><A NAME="htoc68">5.11</A>  Keyboard input

<A NAME="@default402"></A>

The programs we have written so far are a bit rude in the sense that

they accept no input from the user. They just do the same thing every

time.

Python provides a built-in function called raw_input that gets

input from the keyboard<A NAME="text7" HREF="#note7">1</A>. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and raw_input

returns what the user typed as a string.

<A NAME="@default403"></A>

<A NAME="@default404"></A>

<A NAME="@default405"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> input = raw_input()
What are you waiting for?
>>> print input
What are you waiting for?
</FONT></FONT>

Before getting input from the user, it is a good idea to print a

prompt telling the user what to input. raw_input can take a

prompt as an argument:

<A NAME="@default406"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> name = raw_input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
</FONT></FONT>

The sequence \n at the end of the prompt represents a newline,

which is a special character that causes a line break.

That’s why the user’s input appears below the prompt.

<A NAME="@default407"></A>

If you expect the user to type an integer, you can try to convert the return value to int:

<FONT COLOR=blue><FONT SIZE=4>>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
</FONT></FONT>

But if the user types something other than a string of digits, you get an error:

<FONT COLOR=blue><FONT SIZE=4>>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()
</FONT></FONT>

We will see how to handle this kind of error later.

<A NAME="@default408"></A> <A NAME="@default409"></A>

<A NAME="toc62"></A><A NAME="htoc69">5.12</A>  Debugging

<A NAME="whitespace"></A> <A NAME="@default410"></A>

<A NAME="@default411"></A>

The traceback Python displays when an error occurs contains

a lot of information, but it can be overwhelming, especially when there are many frames on the stack. The most

useful parts are usually:

  • What kind of error it was, and
  • Where it occurred.

Syntax errors are usually easy to find, but there are a few

gotchas. Whitespace errors can be tricky because spaces and

tabs are invisible and we are used to ignoring them.

<A NAME="@default412"></A>

<FONT COLOR=blue><FONT SIZE=4>>>> x = 5
>>>  y = 6
  File "<stdin>", line 1
    y = 6
    ^
SyntaxError: invalid syntax
</FONT></FONT>

In this example, the problem is that the second line is indented by

one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code,

sometimes on a previous line.

<A NAME="@default413"></A> <A NAME="@default414"></A>

The same is true of runtime errors. Suppose you are trying

to compute a signal-to-noise ratio in decibels. The formula is SNRdb = 10 log10 (Psignal / Pnoise). In Python,

you might write something like this:

<FONT COLOR=blue><FONT SIZE=4>import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
</FONT></FONT>

But when you run it, you get an error message:

<A NAME="@default415"></A> <A NAME="@default416"></A>

<FONT COLOR=blue><FONT SIZE=4>Traceback (most recent call last):
  File "snr.py", line 5, in ?
    decibels = 10 * math.log10(ratio)
OverflowError: math range error
</FONT></FONT>

The error message indicates line 5, but there is nothing

wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, because dividing two integers does floor division. The solution is to represent signal power

and noise power with floating-point values.

<A NAME="@default417"></A> <A NAME="@default418"></A>

In general, error messages tell you where the problem was discovered, but that is often not where it was caused.

<A NAME="toc63"></A><A NAME="htoc70">5.13</A>  Glossary

modulus operator:
An operator, denoted with a percent sign

(%), that works on integers and yields the remainder when one number is divided by another. <A NAME="@default419"></A>

<A NAME="@default420"></A>
boolean expression:
An expression whose value is either True or False. <A NAME="@default421"></A> <A NAME="@default422"></A>
comparison operator:
One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
logical operator:
One of the operators that combines boolean expressions: and, or, and not.
conditional statement:
A statement that controls the flow of execution depending on some condition. <A NAME="@default423"></A> <A NAME="@default424"></A>
condition:
The boolean expression in a conditional statement that determines which branch is executed. <A NAME="@default425"></A>
compound statement:
A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header. <A NAME="@default426"></A>
body:
The sequence of statements within a compound statement. <A NAME="@default427"></A>
branch:
One of the alternative sequences of statements in a conditional statement. <A NAME="@default428"></A>
chained conditional:
A conditional statement with a series of alternative branches. <A NAME="@default429"></A> <A NAME="@default430"></A>
nested conditional:
A conditional statement that appears in one of the branches of another conditional statement. <A NAME="@default431"></A> <A NAME="@default432"></A>
recursion:
The process of calling the function that is currently executing. <A NAME="@default433"></A>
base case:
A conditional branch in a recursive function that does not make a recursive call. <A NAME="@default434"></A>
infinite recursion:
A function that calls itself recursively without ever reaching the base case. Eventually, an infinite recursion causes a runtime error. <A NAME="@default435"></A>

<A NAME="toc64"></A><A NAME="htoc71">5.14</A>  Exercises

Exercise 1   <A NAME="@default436"></A>

Fermat’s Last Theorem says that there are no integers a, b, and c such that

an + bn = cn 

for any values of n greater than 2.

  1. Write a function named check_fermat that takes four

    parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If

    n is greater than 2 and it turns out to be true that
    an + bn = cn 

    the program should print, “Holy smokes, Fermat was wrong!”

    Otherwise the program should print, “No, that doesn’t work.”

  2. Write a function that prompts the user to input values

    for a, b, c and n, converts them to integers, and uses check_fermat to check whether they

    violate Fermat’s theorem.
Exercise 2   <A NAME="@default437"></A>

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

“If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can<A NAME="text8" HREF="#note8">2</A>.”

  1. Write a function named is_triangle that takes three

    integers as arguments, and that prints either “Yes” or “No,” depending on whether you can or cannot form a triangle from sticks with the

    given lengths.
  2. Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.

The following exercises use TurtleWorld from Chapter <A HREF="book005.html#turtlechap">4</A>:

<A NAME="@default438"></A>

Exercise 3  

Read the following function and see if you can figure out what it does. Then run it (see the examples in Chapter <A HREF="book005.html#turtlechap">4</A>).

<EM><FONT COLOR=blue><FONT SIZE=4>def draw(t, length, n):
    if n == 0:
        return
    angle = 50
    fd(t, length*n)
    lt(t, angle)
    draw(t, length, n-1)
    rt(t, 2*angle)
    draw(t, length, n-1)
    lt(t, angle)
    bk(t, length*n)
</FONT></FONT></EM>
Exercise 4  

<A NAME="@default439"></A>

The Koch curve is a fractal that looks something like this:

<IMG SRC="book008.png">

To draw a Koch curve with length x, all you have to do is

  1. Draw a Koch curve with length x/3.
  2. Turn left 60 degrees.
  3. Draw a Koch curve with length x/3.
  4. Turn right 120 degrees.
  5. Draw a Koch curve with length x/3.
  6. Turn left 60 degrees.
  7. Draw a Koch curve with length x/3.

The only exception is if x is less than 3. In that case, you can just draw a straight line with length x.

  1. Write a function called koch that takes a turtle and

    a length as parameters, and that uses the turtle to draw a Koch

    curve with the given length.
  2. Write a function called snowflake that draws three Koch curves to make the outline of a snowflake.

    You can see my solution at thinkpython.com/code/koch.py.

  3. The Koch curve can be generalized in several ways. See

    wikipedia.org/wiki/Koch_snowflake for examples and

    implement your favorite.

<A NAME="note7" HREF="#text7">1</A>
In Python 3.0, this function is named input
<A NAME="note8" HREF="#text8">2</A>
If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.

<A HREF="book005.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="book007.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>