AchillesGames

Think Python/Print version – Wikibooks, open books for an open world

A(M,N)={n+1if m=0A(m1,1)if m>0 and n=0A(m1,A(m,n1))if m>0 and n>0{displaystyle A(M,N)={begin{cases}n+1&{mbox{if }}m=0\A(m-1,1)&{mbox{if }}m>0{mbox{ and }}n=0\A(m-1,A(m,n-1))&{mbox{if }}m>0{mbox{ and }}n>0end{cases}}}

Exercise 6[edit]

A palindrome is a word that is spelled the same backward and
forward, like “noon” and “redivider”. 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:

def first(word):
    return word[0]

def last(word):
    return word[-1]

def middle(word):
    return word[1:-1]

We’ll see how they work in Chapter ‘8′.

  • Type these functions into a file named ‘palindrome.py

and test them out. What happens if you call ‘middle with
a string with two letters? One letter? What about the empty
string, which is written ' and contains no letters?

  • Write a function called is_palindrome that takes

a string argument and returns ‘True if it is a palindrome
and ‘False otherwise. Remember that you can use the
built-in function ‘len to check the length of a string.

Exercise 7[edit]

A number, ‘a, is a power of ‘b if it is divisible by ‘b
and ‘a/b is a power of ‘b. Write a function called
is_power that takes parameters ‘a and ‘b
and returns ‘True if ‘a is a power of ‘b.

Exercise 8[edit]

The greatest common divisor (GCD) of ‘a and ‘b is the largest number
that divides both of them with no remainder[4].

One way to find the GCD of two numbers is Euclid’s algorithm,
which is based on the observation that if ‘r is the remainder
when ‘a is divided by ‘b, then ‘gcd(a, b) = gcd(b, r)’.
As a base case, we can consider ‘gcd(a, 0) = a.

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

  1. See
    wikipedia.org/wiki/Fibonacci_number.
  2. See
    wikipedia.org/wiki/Gamma_function.
  3. See
    wikipedia.org/wiki/Ackermann_function
  4. This exercise is
    based on an example from Abelson and Sussman’s Structure and
    Interpretation of Computer Programs.

Multiple assignment[edit]

As you may have discovered, it is legal to
make more than one assignment to the same variable. A
new assignment makes an existing variable refer to a new
value (and stop referring to the old value).

bruce = 5
print bruce,
bruce = 7
print bruce

The output of this program is 5 7, because the first time bruce is printed, its value is 5, and the second time, its value is 7. The comma at the end of the first print statement suppresses the newline, which is why both outputs appear on the same line.

Here is what multiple assignment looks like in a state diagram:

With multiple assignment it is especially important to distinguish
between an assignment operation and a statement of equality. Because
Python uses the equal sign (=) for assignment, it is tempting to
interpret a statement like a = b as a statement of equality. It
is not!

First, equality is a symmetric relation and assignment is not. For
example, in mathematics, if a = 7 then 7 = a. But in Python, the
statement a = 7 is legal and 7 = a is not.

Furthermore, in mathematics, a statement of equality is either true or
false, for all time. If a = b now, then a will always equal b.
In Python, an assignment statement can make two variables equal, but
they don’t have to stay that way:

a = 5
b = a    # a and b are now equal
a = 3    # a and b are no longer equal

The third line changes the value of a but does not change the
value of b, so they are no longer equal.

Although multiple assignment is frequently helpful, you should use it
with caution. If the values of variables change frequently, it can
make the code difficult to read and debug.

Updating variables[edit]

One of the most common forms of multiple assignment is an update,
where the new value of the variable depends on the old.

x = x+1

This means “get the current value of x, add one, and then
update x with the new value.”

If you try to update a variable that doesn’t exist, you get an
error, because Python evaluates the right side before it assigns
a value to x:

>>> x = x+1
NameError: name 'x' is not defined

Before you can update a variable, you have to initialize
it, usually with a simple assignment:

>>> x = 0
>>> x = x+1

Updating a variable by adding 1 is called an increment;
subtracting 1 is called a decrement.

The while statement[edit]

Computers are often used to automate repetitive tasks. Repeating
identical or similar tasks without making errors is something that
computers do well and people do poorly.

We have seen two programs, countdown and print_n, that
use recursion to perform repetition, which is also called iteration. Because iteration is so common, Python provides several
language features to make it easier. One is the for statement
we saw in Section 4.2. We’ll get back to that later.

Another is the while statement. Here is a version of countdown that uses a while statement:

def countdown(n):
    while n > 0:
        print n
        n = n-1
    print 'Blastoff!'

You can almost read the while statement as if it were English.
It means, “While n is greater than 0,
display the value of n and then reduce the value of
n by 1. When you get to 0, display the word Blastoff!

More formally, here is the flow of execution for a while statement:

  • Evaluate the condition, yielding True or False.
  • If the condition is false, exit the while statement and continue execution at the next statement.
  • If the condition is true, execute the body and then go back to step 1.

This type of flow is called a loop because the third step
loops back around to the top.

The body of the loop should change the value of one or more variables
so that eventually the condition becomes false and the loop
terminates. Otherwise the loop will repeat forever, which is called
an infinite loop. An endless source of amusement for computer
scientists is the observation that the directions on shampoo,
“Lather, rinse, repeat,” are an infinite loop.

In the case of countdown, we can prove that the loop
terminates because we know that the value of n is finite, and we
can see that the value of n gets smaller each time through the
loop, so eventually we have to get to 0. In other
cases, it is not so easy to tell:

def sequence(n):
    while n != 1:
        print n,
        if n%2 == 0:        # n is even
            n = n/2
        else:               # n is odd
            n = n*3+1

The condition for this loop is n != 1, so the loop will continue
until n is 1, which makes the condition false.

Each time through the loop, the program outputs the value of n
and then checks whether it is even or odd. If it is even, n is
divided by 2. If it is odd, the value of n is replaced with
n*3+1. For example, if the argument passed
to sequence is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.

Since n sometimes increases and sometimes decreases, there is no
obvious proof that n will ever reach 1, or that the program
terminates. For some particular values of n, we can prove
termination. For example, if the starting value is a power of two,
then the value of n will be even each time through the loop
until it reaches 1. The previous example ends with such a sequence,
starting with 16.

The hard question is whether we can prove that this program terminates
for all positive values of n. So far1, no one has
been able to prove it or disprove it!

Exercise 1  

Rewrite the function print_n from
Section ‘5.8′ using iteration instead of recursion.

Sometimes you don’t know it’s time to end a loop until you get half
way through the body. In that case you can use the break
statement to jump out of the loop.

For example, suppose you want to take input from the user until they
type done. You could write:

while True:
    line = raw_input('> ')
    if line == 'done':
        break
    print line

print 'Done!'

The loop condition is True, which is always true, so the
loop runs until it hits the break statement.

Each time through, it prompts the user with an angle bracket.
If the user types done, the break statement exits
the loop. Otherwise the program echoes whatever the user types
and goes back to the top of the loop. Here’s a sample run:

> not done
not done
> done
Done!

This way of writing while loops is common because you
can check the condition anywhere in the loop (not just at the
top) and you can express the stop condition affirmatively
(“stop when this happens”) rather than negatively (“keep going
until that happens.”).

Square roots[edit]

Loops are often used in programs that compute
numerical results by starting with an approximate answer and
iteratively improving it.

For example, one way of computing square roots is Newton’s method.
Suppose that you want to know the square root of a. If you start
with almost any estimate, x, you can compute a better
estimate with the following formula:

For example, if a is 4 and x is 3:

>>> a = 4.0
>>> x = 3.0
>>> y = (x + a/x) / 2
>>> print y
2.16666666667

Which is closer to the correct answer (√4 = 2). If we
repeat the process with the new estimate, it gets even closer:

>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00641025641

After a few more updates, the estimate is almost exact:

>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00001024003
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00000000003

In general we don’t know ahead of time how many steps it takes
to get to the right answer, but we know when we get there
because the estimate
stops changing:

>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.0
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.0

When y == x, we can stop. Here is a loop that starts
with an initial estimate, x, and improves it until it
stops changing:

while True:
    print x
    y = (x + a/x) / 2
    if y == x:
        break
    x = y

For most values of a this works fine, but in general it is
dangerous to test float equality.
Floating-point values are only approximately right:
most rational numbers, like 1/3, and irrational numbers, like
2, can’t be represented exactly with a float.

Rather than checking whether x and y are exactly equal, it
is safer to use the built-in function abs to compute the
absolute value, or magnitude, of the difference between them:

    if abs(y-x) < epsilon:
        break

Where epsilon has a value like 0.0000001 that
determines how close is close enough.

Exercise 2  

'

Encapsulate this loop in a function called square_root
that takes 'a' as a parameter, chooses a reasonable
value of 'x', and returns an estimate of the square root
of 'a'.

Algorithms[edit]

Newton’s method is an example of an algorithm: it is a
mechanical process for solving a category of problems (in this
case, computing square roots).

It is not easy to define an algorithm. It might help to start
with something that is not an algorithm. When you learned
to multiply single-digit numbers, you probably memorized the
multiplication table. In effect, you memorized 100 specific solutions.
That kind of knowledge is not algorithmic.

But if you were “lazy,” you probably cheated by learning a few
tricks. For example, to find the product of n and 9, you can
write n−1 as the first digit and 10−n as the second
digit. This trick is a general solution for multiplying any
single-digit number by 9. That’s an algorithm!

Similarly, the techniques you learned for addition with carrying,
subtraction with borrowing, and long division are all algorithms. One
of the characteristics of algorithms is that they do not require any
intelligence to carry out. They are mechanical processes in which
each step follows from the last according to a simple set of rules.

In my opinion, it is embarrassing that humans spend so much time in
school learning to execute algorithms that, quite literally, require
no intelligence.

On the other hand, the process of designing algorithms is interesting,
intellectually challenging, and a central part of what we call
programming.

Some of the things that people do naturally, without difficulty or
conscious thought, are the hardest to express algorithmically.
Understanding natural language is a good example. We all do it, but
so far no one has been able to explain how we do it, at least
not in the form of an algorithm.

Debugging[edit]

As you start writing bigger programs, you might find yourself
spending more time debugging. More code means more chances to
make an error and more place for bugs to hide.

One way to cut your debugging time is “debugging by bisection.”
For example, if there are 100 lines in your program and you
check them one at a time, it would take 100 steps.

Instead, try to break the problem in half. Look at the middle
of the program, or near it, for an intermediate value you
can check. Add a print statement (or something else
that has a verifiable effect) and run the program.

If the mid-point check is incorrect, the problem must be in the
first half of the program. If it is correct, the problem is
in the second half.

Every time you perform a check like this, you halve the number
of lines you have to search. After six steps (which is much
less than 100), you would be down to one or two lines of code,
at least in theory.

In practice it is not always clear what
the “middle of the program” is and not always possible to
check it. It doesn’t make sense to count lines and find the
exact midpoint. Instead, think about places
in the program where there might be errors and places where it
is easy to put a check. Then choose a spot where you
think the chances are about the same that the bug is before
or after the check.

Glossary[edit]

multiple assignment:
Making more than one assignment to the same
variable during the execution of a program.

update:
An assignment where the new value of the variable
depends on the old.
initialize:
An assignment that gives an initial value to
a variable that will be updated.
increment:
An update that increases the value of a variable
(often by one).
decrement:
An update that decreases the value of a variable.
iteration:
Repeated execution of a set of statements using
either a recursive function call or a loop.
infinite loop:
A loop in which the terminating condition is
never satisfied.

Exercises[edit]

Exercise 3[edit]

To test the square root algorithm in this chapter, you could compare
it with 'math.sqrt'. Write a function named test_square_root
that prints a table like this:

''1.0 1.0           1.0           0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0           2.0           0.0
5.0 2.2360679775  2.2360679775  0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0           3.0           0.0

''

The first column is a number, 'a'; the second column is
the square root of 'a' computed with the function from
Exercise '7.2'; the third column is the square root computed
by 'math.sqrt'; the fourth column is the absolute value
of the difference between the two estimates.

Exercise 4[edit]

The built-in function 'eval' takes a string and evaluates
it using the Python interpreter. For example:

''>>> eval('1 + 2 * 3')
7
>>> import math
>>> eval('math.sqrt(5)')
2.2360679774997898
>>> eval('type(math.pi)')

''

Write a function called eval_loop that iteratively
prompts the user, takes the resulting input and evaluates
it using 'eval', and prints the result.

It should continue until the user enters done, and then
return the value of the last expression it evaluated.

Exercise 5[edit]

The brilliant mathematician Srinivasa Ramanujan found an
infinite series2
that can be used to generate a numerical
approximation of

π{displaystyle pi }

:

1π=229801k=0(4k)!(1103+26390k)(k!)43964k{displaystyle {frac {1}{pi }}={frac {2{sqrt {2}}}{9801}}sum _{k=0}^{infty }{frac {(4k)!(1103+26390k)}{(k!)^{4}396^{4k}}}}

Write a function called estimate_pi that uses this formula
to compute and return an estimate of 'π'. It should use a 'while'
loop to compute terms of the summation until the last term is
smaller than '1e-15' (which is Python notation for '10−15).
You can check the result by comparing it to 'math.pi'.

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

A string is a sequence[edit]

A string is a sequence of characters.
You can access the characters one at a time with the
bracket operator:

>>> fruit="banana"
>>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.

The expression in brackets is called an index.
The index indicates which character in the sequence you
want (hence the name).

But you might not get what you expect:

>>> print letter
a

For most people, the first letter of 'banana' is b, not
a. But for computer scientists, the index is an offset from the
beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0]
>>> print letter
b

So b is the 0th letter (“zero-eth”) of 'banana', a
is the 1th letter (“one-eth”), and n is the 2th (“two-eth”)
letter.

You can use any expression, including variables and operators, as an
index, but the value of the index has to be an integer. Otherwise you
get:

>>> letter = fruit[1.5]
TypeError: string indices must be integers

len is a built-in function that returns the number of characters
in a string:

>>> fruit="banana"
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something
like this:

>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in ’banana’ with the index 6. Since we started counting at zero, the
six letters are numbered 0 to 5. To get the last character, you have
to subtract 1 from length:

>>> last = fruit[length-1]
>>> print last
a

Alternatively, you can use negative indices, which count backward from
the end of the string. The expression fruit[-1] yields the last
letter, fruit[-2] yields the second to last, and so on.

Traversal with a for loop[edit]

A lot of computations involve processing a string one character at a
time. Often they start at the beginning, select each character in
turn, do something to it, and continue until the end. This pattern of
processing is called a traversal. One way to write a traversal
is with a while loop:

index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index = index + 1

This loop traverses the string and displays each letter on a line by
itself. The loop condition is index < len(fruit), so
when index is equal to the length of the string, the
condition is false, and the body of the loop is not executed. The
last character accessed is the one with the index len(fruit)-1,
which is the last character in the string.

Exercise 1  

Write a function that takes a string as an argument
and displays the letters backward, one per line.

Another way to write a traversal is with a for loop:

for char in fruit:
    print char

Each time through the loop, the next character in the string is assigned
to the variable char. The loop continues until no characters are
left.

The following example shows how to use concatenation (string addition)
and a for loop to generate an abecedarian series (that is, in
alphabetical order). In Robert McCloskey’s book Make
Way for Ducklings, the names of the ducklings are Jack, Kack, Lack,
Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in
order:

prefixes="JKLMNOPQ"
suffix = 'ack'

for letter in prefixes:
    print letter + suffix

The output is:

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Of course, that’s not quite right because “Ouack” and
“Quack” are misspelled.

Exercise 2[edit]

Modify the program to fix this error.

String slices[edit]

A segment of a string is called a slice. Selecting a slice is
similar to selecting a character:

>>> s="Monty Python"
>>> print s[0:5]
Monty
>>> print s[6:13]
Python

The operator [n:m] returns the part of the string from the
“n-eth” character to the “m-eth” character, including the first but
excluding the last. This behavior is counterintuitive, but it might
help to imagine the indices pointing between the
characters, as in the following diagram:

If you omit the first index (before the colon), the slice starts at
the beginning of the string. If you omit the second index, the slice
goes to the end of the string:

>>> fruit="banana"
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result
is an empty string, represented by two quotation marks:

>>> fruit="banana"
>>> fruit[3:3]
''

An empty string contains no characters and has length 0, but other
than that, it is the same as any other string.

Exercise 3[edit]

Given that 'fruit' is a string, what does
'fruit[:]' mean?

Strings are immutable[edit]

It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in a string.
For example:

>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: object does not support item assignment

The “object” in this case is the string and the “item” is
the character you tried to assign. For now, an object is
the same thing as a value, but we will refine that definition
later. An item is one of the values in a sequence.

The reason for the error is that
strings are immutable, which means you can’t change an
existing string. The best you can do is create a new string
that is a variation on the original:

>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!

This example concatenates a new first letter onto
a slice of greeting. It has no effect on
the original string.

Searching[edit]

What does the following function do?

def find(word, letter):
    index = 0
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

In a sense, find is the opposite of the [] operator.
Instead of taking an index and extracting the corresponding character,
it takes a character and finds the index where that character
appears. If the character is not found, the function returns -1.

This is the first example we have seen of a return statement
inside a loop. If word[index] == letter, the function breaks
out of the loop and returns immediately.

If the character doesn’t appear in the string, the program
exits the loop normally and returns -1.

This pattern of computation—traversing a sequence and returning
when we find what we are looking for—is a called a search.

Exercise 4[edit]

Modify 'find' so that it has a
third parameter, the index in 'word' where it should start
looking.

Looping and counting[edit]

The following program counts the number of times the letter a
appears in a string:

word = 'banana'
count = 0
for letter in word:
    if letter == 'a':
        count = count + 1
print count

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then
incremented each time an a is found.
When the loop exits, count
contains the result—the total number of a’s.

Exercise 5  


Encapsulate this code in a function named 'count', and generalize it so that it accepts the string and the
letter as arguments.

Exercise 6  

Rewrite this function so that instead of
traversing the string, it uses the three-parameter version of 'find' from the previous section.

string methods[edit]

A method is similar to a function—it takes arguments and
returns a value—but the syntax is different. For example, the
method upper takes a string and returns a new string with
all uppercase letters:

Instead of the function syntax upper(word), it uses
the method syntax word.upper().

>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no
argument.

A method call is called an invocation; in this case, we would
say that we are invoking upper on the word.

As it turns out, there is a string method named find that
is remarkably similar to the function we wrote:

>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1

In this example, we invoke find on word and pass
the letter we are looking for as a parameter.

Actually, the find method is more general than our function;
it can find substrings, not just characters:

>>> word.find('na')
2

It can take as a second argument the index where it should start:

>>> word.find('na', 3)
4

And as a third argument the index where it should stop:

>>> name="bob"
>>> name.find('b', 1, 2)
-1

This search fails because b does not
appear in the index range from 1 to 2 (not including 2).

Exercise 7  

'

There is a string method called 'count' that is similar
to the function in the previous exercise. Read the documentation
of this method
and write an invocation that counts the number of 'a's
in banana.

The in operator[edit]

The word in is a boolean operator that takes two strings and
returns True if the first appears as a substring in the second:

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

For example, the following function prints all the
letters from word1 that also appear in word2:

def in_both(word1, word2):
    for letter in word1:
        if letter in word2:
            print letter

With well-chosen variable names,
Python sometimes reads like English. You could read
this loop, “for (each) letter in (the first) word, if (the) letter
(appears) in (the second) word, print (the) letter.”

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges')
a
e
s

String comparison[edit]

The comparison operators work on strings. To see if two strings are equal:

if word == 'banana':
    print  'All right, bananas.'

Other comparison operations are useful for putting words in alphabetical
order:

if word < 'banana':
    print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
    print 'Your word,' + word + ', comes after banana.'
else:
    print 'All right, bananas.'

Python does not handle uppercase and lowercase letters the same way
that people do. All the uppercase letters come before all the
lowercase letters, so:

Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a
standard format, such as all lowercase, before performing the
comparison. Keep that in mind in case you have to defend yourself
against a man armed with a Pineapple.

Debugging[edit]

When you use indices to traverse the values in a sequence,
it is tricky to get the beginning and end of the traversal
right. Here is a function that is supposed to compare two
words and return True if one of the words is the reverse
of the other, but it contains two errors:

def is_reverse(word1, word2):
    if len(word1) != len(word2):
        return False
    
    i = 0
    j = len(word2)

    while j > 0:
        if word1[i] != word2[j]:
            return False
        i = i+1
        j = j-1

    return True

The first if statement checks whether the words are the
same length. If not, we can return False immediately
and then, for the rest of the function, we can assume that the words
are the same length. This is an example of the guardian pattern
in Section 6.8.

i and j are indices: i traverses word1
forward while j traverses word2 backward. If we find
two letters that don’t match, we can return False immediately.
If we get through the whole loop and all the letters match, we
return True.

If we test this function with the words “pots” and “stop”, we
expect the return value True, but we get an IndexError:

>>> is_reverse('pots', 'stop')
...
  File "reverse.py", line 15, in is_reverse
    if word1[i] != word2[j]:
IndexError: string index out of range

For debugging this kind of error, my first move is to
print the values of the indices immediately before the line
where the error appears.

    while j > 0:
        print i, j        # print here
        
        if word1[i] != word2[j]:
            return False
        i = i+1
        j = j-1

Now when I run the program again, I get more information:

>>> is_reverse('pots', 'stop')
0 4
...
IndexError: string index out of range

The first time through the loop, the value of j is 4,
which is out of range for the string 'pots'.
The index of the last character is 3, so the
initial value for j should be len(word2)-1.

If I fix that error and run the program again, I get:

>>> is_reverse('pots', 'stop')
0 3
1 2
2 1
True

This time we get the right answer, but it looks like the loop only ran
three times, which is suspicious. To get a better idea of what is
happening, it is useful to draw a state diagram. During the first
iteration, the frame for is_reverse looks like this:

I took a little license by arranging the variables in the frame
and adding dotted lines to show that the values of i and
j indicate characters in word1 and word2.

Exercise 8  

'
Starting with this diagram, execute the program on paper, changing the
values of 'i' and 'j' during each iteration. Find and fix the
second error in this function.

Glossary[edit]

object:
Something a variable can refer to. For now,
you can use “object” and “value” interchangeably.
sequence:
An ordered set; that is, a set of
values where each value is identified by an integer index.
item:
One of the values in a sequence.
index:
An integer value used to select an item in
a sequence, such as a character in a string.
slice:
A part of a string specified by a range of indices.
empty string:
A string with no characters and length 0, represented
by two quotation marks.
immutable:
The property of a sequence whose items cannot
be assigned.
traverse:
To iterate through the items in a sequence,
performing a similar operation on each.
search:
A pattern of traversal that stops
when it finds what it is looking for.

counter:
A variable used to count something, usually initialized
to zero and then incremented.
method:
A function that is associated with an object and called
using dot notation.
invocation:
A statement that calls a method.

Exercises[edit]

Exercise 9[edit]

A string slice can take a third index that specifies the “step
size;” that is, the number of spaces between successive characters.
A step size of 2 means every other character; 3 means every third,
etc.

''>>> fruit="banana"
>>> fruit[0:5:2]
'bnn'
''

A step size of -1 goes through the word backwards, so
the slice [::-1] generates a reversed string.

Use this idiom to write a one-line version of is_palindrome
from Exercise '6.6'.

Exercise 10[edit]

Read the documentation of the string methods at
'docs.python.org/lib/string-methods.html'. You
might want to experiment with some of them to make sure
you understand how they work. 'strip' and
'replace' are particularly useful.

The documentation uses a syntax that might be confusing.
For example, in find(sub[, start[, end]]), the brackets
indicate optional arguments. So 'sub' is required, but
'start' is optional, and if you include 'start',
then 'end' is optional.

Exercise 11[edit]

The following functions are all intended to check whether a
string contains any lowercase letters, but at least some of them are

wrong. For each function, describe what the function actually does.

''def any_lowercase1(s):
    for c in s:
        if c.islower():
            return True
        else:
            return False

def any_lowercase2(s):
    for c in s:
        if 'c'.islower():
            return 'True'
        else:
            return 'False'

def any_lowercase3(s):
    for c in s:
        flag = c.islower()
    return flag

def any_lowercase4(s):
    flag = False
    for c in s:
        flag = flag or c.islower()
    return flag

def any_lowercase5(s):
    for c in s:
        if not c.islower():
            return False
    return True
''

Exercise 12[edit]

ROT13 is a weak form of encryption that involves “rotating” each
letter in a word by 13 places[1]. To rotate a letter means
to shift it through the alphabet, wrapping around to the beginning if
necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’.

Write a function called rotate_word
that takes a string and an integer as parameters, and that returns
a new string that contains the letters from the original string
“rotated” by the given amount.

For example, “cheer” rotated by 7 is “jolly” and “melon” rotated
by -10 is “cubed”.

You might want to use the built-in functions 'ord', which converts
a character to a numeric code, and 'chr', which converts numeric
codes to characters.

Potentially offensive jokes on the Internet are sometimes encoded
in ROT13. If you are not easily offended, find and decode some
of them.

  1. See wikipedia.org/wiki/ROT13


Reading word lists[edit]

For the exercises in this chapter we need a list of English words.
There are lots of word lists available on the Web, but the one most
suitable for our purpose is one of the word lists collected and
contributed to the public domain by Grady Ward as part of the Moby
lexicon project[1]. It
is a list of 113,809 official crosswords; that is, words that are
considered valid in crossword puzzles and other word games. In the
Moby collection, the filename is 113809of.fic; I include a copy
of this file, with the simpler name words.txt, along with
Swampy.

This file is in plain text, so you can open it with a text
editor, but you can also read it from Python. (You may need to move the file from the swampy folder into the main python folder) The built-in
function open takes the name of the file as a parameter
and returns a file object you can use to read the file.

>>> fin = open('words.txt')
>>> print fin

fin is a common name for a file object used for
input. Mode 'r' indicates that this file is open for
reading (as opposed to 'w' for writing).

The file object provides several methods for reading, including
readline, which reads characters from the file
until it gets to a newline and returns the result as a
string:

>>> fin.readline()
'aarn'

The first word in this particular list is “aa,” which is a kind of
lava. The sequence rn represents two whitespace characters,
a carriage return and a newline, that separate this word from the
next.

The file object keeps track of where it is in the file, so
if you call readline again, you get the next word:

>>> fin.readline()
'aahrn'

The next word is “aah,” which is a perfectly legitimate
word, so stop looking at me like that.
Or, if it’s the whitespace that’s bothering you,
we can get rid of it with the string method strip:

>>> line = fin.readline()
>>> word = line.strip()
>>> print word
aahed

You can also use a file object as part of a for loop.
This program reads words.txt and prints each word, one
per line:

fin = open('words.txt')
for line in fin:
    word = line.strip()
    print word
Exercise 1  

Write a program that reads 'words.txt' and prints only the
words with more than 20 characters (not counting whitespace).

Exercises[edit]

There are solutions to these exercises in the next section.
You should at least attempt each one before you read the solutions.

Exercise 2  

In 1939 Ernest Vincent Wright published a 50,000 word novel called
Gadsby that does not contain the letter “e.” Since “e” is
the most common letter in English, that’s not easy to do.
In fact, it is difficult to construct a solitary thought without using
that most common symbol. It is slow going at first, but with caution
and hours of training you can gradually gain facility.

All right, I’ll stop now.

Write a function called has_no_e that returns 'True' if
the given word doesn’t have the letter “e” in it.

Modify your program from the previous section to print only the words
that have no “e” and compute the percentage of the words in the list
have no “e.”

Exercise 3  

Write a function named 'avoids'
that takes a word and a string of forbidden letters, and
that returns 'True' if the word doesn’t use any of the forbidden
letters.
Modify your program to prompt the user to enter a string
of forbidden letters and then print the number of words that
don’t contain any of them.
Can you find a combination of 5 forbidden letters that
excludes the smallest number of words?

Exercise 4  

Write a function named uses_only that takes a word and a
string of letters, and that returns 'True' if the word contains
only letters in the list. Can you make a sentence using only the
letters 'acefhlo'? Other than “Hoe alfalfa?”

Exercise 5  

Write a function named uses_all that takes a word and a
string of required letters, and that returns 'True' if the word
uses all the required letters at least once. How many words are there
that use all the vowels 'aeiou'? How about 'aeiouy'?

Exercise 6  

Write a function called is_abecedarian that returns
'True' if the letters in a word appear in alphabetical order
(double letters are ok).
How many abecedarian words are there?

All of the exercises in the previous section have something
in common; they can be solved with the search pattern we saw
in Section 8.6. The simplest example is:

def has_no_e(word):
    for letter in word:
        if letter == 'e':
            return False
    return A=break

The for loop traverses the characters in word. If we find
the letter “e”, we can immediately return False; otherwise we
have to go to the next letter. If we exit the loop normally, that
means we didn’t find an “e”, so we return True.

You can write this function more concisely using the in
operator, but I started with this version because it
demonstrates the logic of the search pattern.

avoids is a more general version of has_no_e but it
has the same structure:

def avoids(word, forbidden):
    for letter in word:
        if letter in forbidden:
            return False
    return True

We can return False as soon as we find a forbidden letter;
if we get to the end of the loop, we return True.

uses_only is similar except that the sense of the condition
is reversed:

def uses_only(word, available):
    for letter in word: 
        if letter not in available:
            return False
    return True

Instead of a list of forbidden words, we have a list of available
words. If we find a letter in word that is not in
available, we can return False.

uses_all is similar except that we reverse the role
of the word and the string of letters:

def uses_all(word, required):
    for letter in required: 
        if letter not in word:
            return False
    return True

Instead of traversing the letters in word, the loop
traverses the required letters. If any of the required letters
do not appear in the word, we can return False.

If you were really thinking like a computer scientist, you would
have recognized that uses_all was an instance of a
previously-solved problem, and you would have written:

def uses_all(word, required):
    return uses_only(required, word)

This is an example of a program development method called problem
recognition, which means that you recognize the problem you are
working on as an instance of a previously-solved problem, and apply a
previously-developed solution.

Looping with indices[edit]

I wrote the functions in the previous section with for
loops because I only needed the characters in the strings; I didn’t
have to do anything with the indices.

For is_abecedarian we have to compare adjacent letters,
which is a little tricky with a for loop:

def is_abecedarian(word):
    previous = word[0]
    for c in word:
        if c < previous:
            return False
        previous = c
    return True

An alternative is to
use recursion:

def is_abecedarian(word):
    if len(word) <= 1:
        return True
    if word[0] > word[1]:
        return False
    return is_abecedarian(word[1:])

Another option is to use a while loop:

def is_abecedarian(word):
    i = 0
    while i < len(word)-1:
        if word[i+1] < word[i]:
            return False
        i = i+1
    return True

The loop starts at i=0 and ends when i=len(word)-1. Each
time through the loop, it compares the ith character (which you can
think of as the current character) to the i+1th character (which you
can think of as the next).

If the next character is less than (alphabetically before) the current
one, then we have discovered a break in the abecedarian trend, and
we return False.

If we get to the end of the loop without finding a fault, then the
word passes the test. To convince yourself that the loop ends
correctly, consider an example like 'flossy'. The
length of the word is 6, so
the last time the loop runs is when i is 4, which is the
index of the second-to-last character. On the last iteration,
it compares the second-to-last character to the last, which is
what we want.

Here is a version of is_palindrome (see
Exercise 6.6) that uses two indices; one starts at the
beginning and goes up; the other starts at the end and goes down.

def is_palindrome(word):
    i = 0
    j = len(word)-1

    while i

Or, if you noticed that this is an instance of a previously-solved
problem, you might have written:

def is_palindrome(word):
    return is_reverse(word, word)

Assuming you did Exercise 8.8.

Debugging[edit]

Testing programs is hard. The functions in this chapter are
relatively easy to test because you can check the results by hand.
Even so, it is somewhere between difficult and impossible to choose a
set of words that test for all possible errors.

Taking has_no_e as an example, there are two obvious
cases to check: words that have an ’e’ should return False;
words that don’t should return True. You should have no
trouble coming up with one of each.

Within each case, there are some less obvious subcases. Among the
words that have an “e,” you should test words with an “e” at the
beginning, the end, and somewhere in the middle. You should test long
words, short words, and very short words, like the empty string. The
empty string is an example of a special case, which is one of
the non-obvious cases where errors often lurk.

In addition to the test cases you generate, you can also test
your program with a word list like words.txt. By scanning
the output, you might be able to catch errors, but be careful:
you might catch one kind of error (words that should not be
included, but are) and not another (words that should be included,
but aren’t).

In general, testing can help you find bugs, but it is not easy to
generate a good set of test cases, and even if you do, you can’t
be sure your program is correct.

According to a legendary computer scientist:

Program testing can be used to show the presence of bugs, but never to
show their absence!
— Edsger W. Dijkstra

Glossary[edit]

file object:
A value that represents an open file.

problem recognition:
A way of solving a problem by
expressing it as an instance of a previously-solved problem.
special case:
A test case that is atypical or non-obvious
(and less likely to be handled correctly).

Exercises[edit]

Exercise 7[edit]

This question is based on a Puzzler that was broadcast on the radio
program Car Talk[2]:

Give me a word with three consecutive double letters. I'll give you a

couple of words that almost qualify, but don't. For example, the word
committee, c-o-m-m-i-t-t-e-e. It would be great except for the ‘i’ that
sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could
take out those i’s it would work. But there is a word that has three
consecutive pairs of letters and to the best of my knowledge this may
be the only word. Of course there are probably 500 more but I can only
think of one. What is the word?

Write a program to find it. You can see my solution at
'thinkpython.com/code/cartalk.py'.

Exercise 8[edit]

Here’s another Car Talk Puzzler[3]:

“I was driving on the highway the other day and I happened to
notice my odometer. Like most odometers, it shows six digits,
in whole miles only. So, if my car had 300,000
miles, for example, I’d see 3-0-0-0-0-0.
“Now, what I saw that day was very interesting. I noticed that the
last 4 digits were palindromic; that is, they read the same forward as
backward. For example, 5-4-4-5 is a palindrome, so my odometer
could have read 3-1-5-4-4-5.

“One mile later, the last 5 numbers were palindromic. For example, it
could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of
6 numbers were palindromic. And you ready for this? One mile later,
all 6 were palindromic!

“The question is, what was on the odometer when I first looked?”

Write a Python program that tests all the six-digit numbers and prints
any numbers that satisfy these requirements. You can see my solution
at 'thinkpython.com/code/cartalk.py'.

Exercise 9[edit]

Here’s another Car Talk Puzzler you can solve with a
search[4]:

“Recently I had a visit with my mom and we realized that
the two digits that make up my age when reversed resulted in her
age. For example, if she’s 73, I’m 37. We wondered how often this has
happened over the years but we got sidetracked with other topics and
we never came up with an answer.
“When I got home I figured out that the digits of our ages have been
reversible six times so far. I also figured out that if we’re lucky it
would happen again in a few years, and if we’re really lucky it would
happen one more time after that. In other words, it would have
happened 8 times over all. So the question is, how old am I now?”

Write a Python program that searches for solutions to this Puzzler.
Hint: you might find the string method 'zfill' useful.

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

  1. wikipedia.org/wiki/Moby_Project
  2. www.cartalk.com/content/puzzler/transcripts/200725
  3. www.cartalk.com/content/puzzler/transcripts/200803
  4. www.cartalk.com/content/puzzler/transcripts/200813


A list is a sequence[edit]

Like a string, a list is a sequence of values. In a string, the
values are characters; in a list, they can be any type. The values in
list are called elements or sometimes items.

There are several ways to create a new list; the simplest is to
enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']

The first example is a list of four integers. The second is a list of
three strings. The elements of a list don’t have to be the same type.
The following list contains a string, a float, an integer, and
(lo!) another list:

['spam', 2.0, 5, [10, 20]]

A list within another list is nested.

A list that contains no elements is
called an empty list; you can create one with empty
brackets, [].

As you might expect, you can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []

Lists are mutable[edit]

The syntax for accessing the elements of a list is the same as for
accessing the characters of a string—the bracket operator. The
expression inside the brackets specifies the index. Remember that the
indices start at 0:

>>> print cheeses[0]
Cheddar

Unlike strings, lists are mutable. When the bracket operator appears
on the left side of an assignment, it identifies the element of the
list that will be assigned.

>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]

The one-eth element of numbers, which
used to be 123, is now 5.

You can think of a list as a relationship between indices and
elements. This relationship is called a mapping; each index
“maps to” one of the elements. Here is a state diagram showing cheeses, numbers and empty:

Lists are represented by boxes with the word “list” outside
and the elements of the list inside. cheeses refers to
a list with three elements indexed 0, 1 and 2.
numbers contains two elements; the diagram shows that the
value of the second element has been reassigned from 123 to 5.
empty refers to a list with no elements.

List indices work the same way as string indices:

  • Any integer expression can be used as an index.
  • If you try to read or write an element that does not exist, you get an IndexError.
  • If an index has a negative value, it counts backward from the end of the list.

The in operator also works on lists.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

Traversing a list[edit]

The most common way to traverse the elements of a list is
with a for loop. The syntax is the same as for strings:

for cheese in cheeses:
    print cheese

This works well if you only need to read the elements of the
list. But if you want to write or update the elements, you
need the indices. A common way to do that is to combine
the functions range and len:

for i in range(len(numbers)):
    numbers[i] = numbers[i] * 2

This loop traverses the list and updates each element. len
returns the number of elements in the list. range returns
a list of indices from 0 to n−1, where n is the length of
the list. Each time through the loop i gets the index
of the next element. The assignment statement in the body uses
i to read the old value of the element and to assign the
new value.

A for loop over an empty list never executes the body:

for x in empty:
    print 'This never happens.'

Although a list can contain another list, the nested
list still counts as a single element. The length of this list is
four:

['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

List operations[edit]

The + operator concatenates lists:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:

>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example
repeats the list [1, 2, 3] three times.

List slices[edit]

The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning.
If you omit the second, the slice goes to the end. So if you
omit both, the slice is a copy of the whole list.

>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy
before performing operations that fold, spindle or mutilate
lists.

A slice operator on the left side of an assignment
can update multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']

List methods[edit]

Python provides methods that operate on lists. For example,
append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']

extend takes a list as an argument and appends all of
the elements:

>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.

sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']

List methods are all void; they modify the list and return None.
If you accidentally write t = t.sort(), you will be disappointed
with the result.

Map, filter and reduce[edit]

To add up all the numbers in a list, you can use a loop like this:

def add_all(t):
    total = 0
    for x in t:
        total += x
    return total

total is initialized to 0. Each time through the loop,
x gets one element from the list. The += operator
provides a short way to update a variable:

    total += x

is equivalent to:

    total = total + x

As the loop executes, total accumulates the sum of the
elements; a variable used this way is sometimes called an
accumulator.

Adding up the elements of a list is such a common operation
that Python provides it as a built-in function, sum:

>>> t = [1, 2, 3]
>>> sum(t)
6

An operation like this that combines a sequence of elements into
a single value is sometimes called reduce.

Sometimes you want to traverse one list while building
another. For example, the following function takes a list of strings
and returns a new list that contains capitalized strings:

def capitalize_all(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

res is initialized with an empty list; each time through
the loop, we append the next element. So res is another
kind of accumulator.

An operation like capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence.

Another common operation is to select some of the elements from
a list and return a sublist. For example, the following
function takes a list of strings and returns a list that contains
only the uppercase strings:

def only_upper(t):
    res = []
    for s in t:
        if s.isupper():
            res.append(s)
    return res

isupper is a string method that returns True if
the string contains only upper case letters.

An operation like only_upper is called a filter because
it selects some of the elements and filters out the others.

Most common list operations can be expressed as a combination
of map, filter and reduce. Because these operations are
so common, Python provides language features to support them,
including the built-in function map and an operator
called a “list comprehension.”

Exercise 1[edit]

Write a function that takes a list of numbers and returns the
cumulative sum; that is, a new list where the 'i'th element
is the sum of the first 'i+1' elements from the original list.
For example, the cumulative sum of '[1, 2, 3]' is
'[1, 3, 6]'.

Deleting elements[edit]

There are several ways to delete elements from a list. If you
know the index of the element you want, you can use
pop:

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b

pop modifies the list and returns the element that was removed.
If you don’t provide an index, it deletes and returns the
last element.

If you don’t need the removed value, you can use the del
operator:

>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']

If you know the element you want to remove (but not the index), you
can use remove:

>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']

The return value from remove is None.

To remove more than one element, you can use del with
a slice index:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

As usual, the slice selects all the elements up to, but not
including, the second index.

Lists and strings[edit]

A string is a sequence of characters and a list is a sequence
of values, but a list of characters is not the same as a
string. To convert from a string to a list of characters,
you can use list:

>>> s="spam"
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

Because list is the name of a built-in function, you should
avoid using it as a variable name. I also avoid l because
it looks too much like 1. So that’s why I use t.

The list function breaks a string into individual letters. If
you want to break a string into words, you can use the split
method:

>>> s="pining for the fjords"
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']

An optional argument called a delimiter specifies which
characters to use as word boundaries. The following example uses a hyphen as a delimiter:

>>> s="spam-spam-spam"
>>> delimiter="-"
>>> s.split(delimiter)
['spam', 'spam', 'spam']

join is the inverse of split. It
takes a list of strings and
concatenates the elements. join is a string method,
so you have to invoke it on the delimiter and pass the
list as a parameter:

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter=" "
>>> delimiter.join(t)
'pining for the fjords'

In this case the delimiter is a space character, so
join puts a space between words. To concatenate
strings without spaces, you can use the empty string,
, as a delimiter.

Objects and values[edit]

If we execute these assignment statements:

a="banana"
b = 'banana'

We know that a and b both refer to a
string, but we don’t
know whether they refer to the same string.
There are two possible states:

In one case, a and b refer to two different objects that
have the same value. In the second case, they refer to the same
object.

To check whether two variables refer to the same object, you can
use the is operator.

>>> a="banana"
>>> b = 'banana'
>>> a is b
True

In this example, Python only created one string object,
and both a and b refer to it.

But when you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

So the state diagram looks like this:

In this case we would say that the two lists are equivalent,
because they have the same elements, but not identical, because
they are not the same object. If two objects are identical, they are
also equivalent, but if they are equivalent, they are not necessarily
identical.

Until now, we have been using “object” and “value”
interchangeably, but it is more precise to say that an object has a
value. If you execute a = [1,2,3], a refers to a list
object whose value is a particular sequence of elements. If another
list has the same elements, we would say it has the same value.

Aliasing[edit]

If a refers to an object and you assign b = a,
then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

The state diagram looks like this:

The association of a variable with an object is called a reference. In this example, there are two references to the same
object.

An object with more than one reference has more
than one name, so we say that the object is aliased.

If the aliased object is mutable,
changes made with one alias affect
the other:

>>> b[0] = 17
>>> print a
[17, 2, 3]

Although this behavior can be useful, it is error-prone. In general,
it is safer to avoid aliasing when you are working with mutable
objects.

For immutable objects like strings, aliasing is not as much of a
problem. In this example:

a="banana"
b = 'banana'

It almost never makes a difference whether a and b refer
to the same string or not.

List arguments[edit]

When you pass a list to a function, the function gets a reference
to the list.
If the function modifies a list parameter, the caller sees the change.
For example, delete_head removes the first element from a list:

def delete_head(t):
    del t[0]

Here’s how it is used:

>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']

The parameter t and the variable letters are
aliases for the same object. The stack diagram looks like
this:

Since the list is shared by two frames, I drew
it between them.

It is important to distinguish between operations that
modify lists and operations that create new lists. For
example, the append method modifies a list, but the
+ operator creates a new list:

>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None

>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t2 is t3
False

This difference is important when you write functions that
are supposed to modify lists. For example, this function
does not delete the head of a list:

def bad_delete_head(t):
    t = t[1:]              # WRONG!

The slice operator creates a new list and the assignment
makes t refer to it, but none of that has any effect
on the list that was passed as an argument.

An alternative is to write a function that creates and
returns a new list. For
example, tail returns all but the first
element of a list:

def tail(t):
    return t[1:]

This function leaves the original list unmodified.
Here’s how it is used:

>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']

Exercise 2[edit]

Write a function called 'chop' that takes a list and modifies
it, removing the first and last elements, and returns 'None'.

Then write a function called 'middle' that takes a list and
returns a new list that contains all but the first and last
elements.

Debugging[edit]

Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:

  • Don’t forget that most list methods modify the argument and

return None. This is the opposite of the string methods,
which return a new string and leave the original alone.
If you are used to writing string code like this:

word = word.strip()

It is tempting to write list code like this:

t = t.sort()           # WRONG!

Because sort returns None, the
next operation you perform with t is likely to fail.

Before using list methods and operators, you should read the
documentation carefully and then test them in interactive mode. The
methods and operators that lists share with other sequences (like
strings) are documented at
docs.python.org/lib/typesseq.html. The
methods and operators that only apply to mutable sequences
are documented at docs.python.org/lib/typesseq-mutable.html.

  • Pick an idiom and stick with it.

Part of the problem with lists is that there are too many
ways to do things. For example, to remove an element from
a list, you can use pop, remove, del,
or even a slice assignment.

To add an element, you can use the append method or
the + operator. But don’t forget that these are right:

t.append(x)
t = t + [x]

And these are wrong:

t.append([x])          # WRONG!
t = t.append(x)        # WRONG!
t + [x]                # WRONG!
t = t + x              # WRONG!

Try out each of these examples in interactive mode to make sure
you understand what they do. Notice that only the last
one causes a runtime error; the other three are legal, but they
do the wrong thing.

  • Make copies to avoid aliasing.

If you want to use a method like sort that modifies
the argument, but you need to keep the original list as
well, you can make a copy.

orig = t[:]
t.sort()

In this example you could also use the built-in function sorted,
which returns a new, sorted list and leaves the original alone.
But in that case you should avoid using sorted as a variable
name!

Glossary[edit]

list:
A sequence of values.
element:
One of the values in a list (or other sequence),
also called items.
index:
An integer value that indicates an element in a list.
nested list:
A list that is an element of another list.
list traversal:
The sequential accessing of each element in a list.
mapping:
A relationship in which each element of one set
corresponds to an element of another set. For example, a list is
a mapping from indices to elements.
accumulator:
A variable used in a loop to add up or
accumulate a result.

reduce:
A processing pattern that traverses a sequence
and accumulates the elements into a single result.

map:
A processing pattern that traverses a sequence and
performs an operation on each element.

filter:
A processing pattern that traverses a list and
selects the elements that satisfy some criterion.

object:
Something a variable can refer to. An object
has a type and a value.
equivalent:
Having the same value.
identical:
Being the same object (which implies equivalence).
reference:
The association between a variable and its value.
aliasing:
A circumstance where two variables refer to the same
object.
delimiter:
A character or string used to indicate where a
string should be split.

Exercises[edit]

Exercise 3[edit]

Write a function called is_sorted that takes a list as a
parameter and returns 'True' if the list is sorted in ascending
order and 'False' otherwise. You can assume (as a precondition)
that the elements of the list can be compared with the comparison
operators '<', '>', etc.

For example, is_sorted([1,2,2]) should return 'True'
and is_sorted(['b','a']) should return 'False'.

Exercise 4[edit]

Two words are anagrams if you can rearrange the letters from one
to spell the other. Write a function called is_anagram
that takes two strings and returns 'True' if they are anagrams.

Exercise 5  


The (so-called) Birthday Paradox:



Write a function called has_duplicates that takes
a list and returns 'True' if there is any element that
appears more than once. It should not modify the original
list.

  • If there are 23 students in your class, what are the chances

that two of you have the same birthday? You can estimate this
probability by generating random samples of 23 birthdays
and checking for matches. Hint: you can generate random birthdays
with the 'randint' function in the 'random' module.

You can read about this problem at
'wikipedia.org/wiki/Birthday_paradox', and you can see my solution
at 'thinkpython.com/code/birthday.py'.

Exercise 6  

Write a function called remove_duplicates that takes
a list and returns a new list with only the unique elements from
the original. Hint: they don’t have to be in the same order.

Exercise 7[edit]

Write a function that reads the file 'words.txt' and builds
a list with one element per word. Write two versions of
this function, one using the 'append' method and the
other using the idiom 't = t + [x]'. Which one takes
longer to run? Why?

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

Exercise 8[edit]

To check whether a word is in the word list, you could use
the 'in' operator, but it would be slow because it searches
through the words in order.

Because the words are in alphabetical order, we can speed things up
with a bisection search, which is similar to what you do when you look
a word up in the dictionary. You start in the middle and check to see
whether the word you are looking for comes before the word in the
middle of the list. If so, then you search the first half of the list
the same way. Otherwise you search the second half.

Either way, you cut the remaining search space in half. If the
word list has 113,809 words, it will take about 17 steps to
find the word or conclude that it’s not there.

Write a function called 'bisect' that takes a sorted list
and a target value and returns the index of the value
in the list, if it’s there, or 'None' if it’s not.

Or you could read the documentation of the 'bisect' module
and use that!

Exercise 9[edit]

Two words are a “reverse pair” if each is the reverse of the
other. Write a program that finds all the reverse pairs in the
word list.

Exercise 10[edit]

Two words “interlock” if taking alternating letters from each forms
a new word1. For example, “shoe” and “cold”
interlock to form “schooled.”

  • Write a program that finds all pairs of words that interlock.

Hint: don’t enumerate all pairs!

  • Can you find any words that are three-way interlocked; that is,

every third letter forms a word, starting from the first, second or
third?

A dictionary is like a list, but more general. In a list,
the indices have to be integers; in a dictionary they can
be (almost) any type.

You can think of a dictionary as a mapping between a set of indices
(which are called keys) and a set of values. Each key maps to a
value. The association of a key and a value is called a key-value pair or sometimes an item.

As an example, we'll build a dictionary that maps from English
to Spanish words, so the keys and the values are all strings.

The function dict creates a new dictionary with no items.
Because dict is the name of a built-in function, you
should avoid using it as a variable name.

>>> eng2sp = dict()
>>> print eng2sp
{}

The squiggly-brackets, {}, represent an empty dictionary.
To add items to the dictionary, you can use square brackets:

>>> eng2sp['one'] = 'uno'

This line creates an item that maps from the key
’one’ to the value 'uno'. If we print the
dictionary again, we see a key-value pair with a colon
between the key and value:

>>> print eng2sp
{'one': 'uno'}

This output format is also an input format. For example,
you can create a new dictionary with three items:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

But if you print eng2sp, you might be surprised:

>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}

The order of the key-value pairs is not the same. In fact, if
you type the same example on your computer, you might get a
different result. In general, the order of items in
a dictionary is unpredictable.

But that’s not a problem because
the elements of a dictionary are never indexed with integer indices.
Instead, you use the keys to look up the corresponding values:

>>> print eng2sp['two']
'dos'

The key ’two’ always maps to the value 'dos' so the order
of the items doesn’t matter.

If the key isn’t in the dictionary, you get an exception:

>>> print eng2sp['four']
KeyError: 'four'

The len function works on dictionaries; it returns the
number of key-value pairs:

>>> len(eng2sp)
3

The in operator works on dictionaries; it tells you whether
something appears as a key in the dictionary (appearing
as a value is not good enough).

>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False

To see whether something appears as a value in a dictionary, you
can use the method values, which returns the values as
a list, and then use the in operator:

>>> vals = eng2sp.values()
>>> 'uno' in vals
True

You can do the same with keys:

>>> kees = eng2sp.keys()
>>> ‘one’ in kees
True

The in operator uses different algorithms for lists and
dictionaries. For lists, it uses a search algorithm, as in
Section 8.6. As the list gets longer, the search time gets
longer in direct proportion. For dictionaries, Python uses an
algorithm called a hashtable that has a remarkable property: the
in operator takes about the same amount of time no matter how
many items there are in a dictionary. I won’t explain how that’s
possible, but you can read more about it at
wikipedia.org/wiki/Hash_table.

Exercise 1[edit]

Write a function that reads the words in 'words.txt' and
stores them as keys in a dictionary. It doesn’t matter what the
values are. Then you can use the 'in' operator
as a fast way to check whether a string is in
the dictionary.

If you did Exercise '10.8', you can compare the speed
of this implementation with the list 'in' operator and the
bisection search.

Dictionary as a set of counters[edit]

Suppose you are given a string and you want to count how many
times each letter appears. There are several ways you could do it:

  • You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.
  • You could create a list with 26 elements. Then you could convert each character to a number (using the built-in function ord), use the number as an index into the list, and increment the appropriate counter.
  • You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item.

Each of these options performs the same computation, but each
of them implements that computation in a different way.

An implementation is a way of performing a computation;
some implementations are better than others. For example,
an advantage of the dictionary implementation is that we don’t
have to know ahead of time which letters appear in the string
and we only have to make room for the letters that do appear.

Here is what the code might look like:

def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

The name of the function is histogram, which is a statistical
term for a set of counters (or frequencies).

The first line of the
function creates an empty dictionary. The for loop traverses
the string. Each time through the loop, if the character c is
not in the dictionary, we create a new item with key c and the
initial value 1 (since we have seen this letter once). If c is
already in the dictionary we increment d[c].

Here’s how it works:

>>> h = histogram('brontosaurus')
>>> print h
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}

The histogram indicates that the letters ’a’ and 'b'
appear once; 'o' appears twice, and so on.

Exercise 2[edit]

Dictionaries have a method called 'get' that takes a key
and a default value. If the key appears in the dictionary,
'get' returns the corresponding value; otherwise it returns
the default value. For example:

''>>> h = histogram('a')
>>> print h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
''

Use 'get' to write 'histogram' more concisely. You
should be able to eliminate the 'if' statement.

Looping and dictionaries[edit]

If you use a dictionary in a for statement, it traverses
the keys of the dictionary. For example, print_hist
prints each key and the corresponding value:

def print_hist(h):
    for c in h:
        print c, h[c]

Here’s what the output looks like:

>>> h = histogram('parrot')
>>> print_hist(h)
a 1
p 1
r 2
t 1
o 1

Again, the keys are in no particular order.

Exercise 3[edit]

Dictionaries have a method called 'keys' that returns
the keys of the dictionary, in no particular order, as a list.

Modify print_hist to print the keys and their values
in alphabetical order.

Reverse lookup[edit]

Given a dictionary d and a key k, it is easy to
find the corresponding value v = d[k]. This operation
is called a lookup.

But what if you have v and you want to find k?
You have two problems: first, there might be more than one
key that maps to the value v. Depending on the application,
you might be able to pick one, or you might have to make
a list that contains all of them. Second, there is no
simple syntax to do a reverse lookup; you have to search.

Here is a function that takes a value and returns the first
key that maps to that value:

def reverse_lookup(d, v):
    for k in d:
        if d[k] == v:
            return k
    raise ValueError

This function is yet another example of the search pattern, but it
uses a feature we haven’t seen before, raise. The raise
statement causes an exception; in this case it causes a ValueError, which generally indicates that there is something wrong
with the value of a parameter.

If we get to the end of the loop, that means v
doesn’t appear in the dictionary as a value, so we raise an
exception.

Here is an example of a successful reverse lookup:

>>> h = histogram('parrot')
>>> k = reverse_lookup(h, 2)
>>> print k
r

And an unsuccessful one:

>>> k = reverse_lookup(h, 3)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 5, in reverse_lookup
ValueError

The result when you raise an exception is the same as when
Python raises one: it prints a traceback and an error message.

The raise statement takes a detailed error message as an
optional argument. For example:

>>> raise ValueError, 'value does not appear in the dictionary'
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: value does not appear in the dictionary

A reverse lookup is much slower than a forward lookup; if you
have to do it often, or if the dictionary gets big, the performance
of your program will suffer.

Exercise 4  

Modify reverse_lookup so that it builds and returns a list
of all keys that map to 'v', or an empty list if there
are none.

Dictionaries and lists[edit]

Lists can appear as values in a dictionary. For example, if you
were given a dictionary that maps from letters to frequencies, you
might want to invert it; that is, create a dictionary that maps
from frequencies to letters. Since there might be several letters
with the same frequency, each value in the inverted dictionary
should be a list of letters.

Here is a function that inverts a dictionary:

def invert_dict(d):
    inv = dict()
    for key in d:
        val = d[key]
        if val not in inv:
            inv[val] = [key]
        else:
            inv[val].append(key)
    return inv

Each time through the loop, key gets a key from d and
val gets the corresponding value. If val is not in inv,
that means we haven’t seen it before, so we create a new item and
initialize it with a singleton (a list that contains a
single element). Otherwise we have seen this value before, so we
append the corresponding key to the list.

Here is an example:

>>> hist = histogram('parrot')
>>> print hist
{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}
>>> inv = invert_dict(hist)
>>> print inv
{1: ['a', 'p', 't', 'o'], 2: ['r']}

And here is a diagram showing hist and inv:

A dictionary is represented as a box with the type dict above it
and the key-value pairs inside. If the values are integers, floats or
strings, I usually draw them inside the box, but I usually draw lists
outside the box, just to keep the diagram simple.

Lists can be values in a dictionary, as this example shows, but they
cannot be keys. Here’s what happens if you try:

>>> t = [1, 2, 3]
>>> d = dict()
>>> d[t] = 'oops'
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: list objects are unhashable

I mentioned earlier that a dictionary is implemented using
a hashtable and that means that the keys have to be hashable.

A hash is a function that takes a value (of any kind)
and returns an integer. Dictionaries use these integers,
called hash values, to store and look up key-value pairs.

This system works fine if the keys are immutable. But if the
keys are mutable, like lists, bad things happen. For example,
when you create a key-value pair, Python hashes the key and
stores it in the corresponding location. If you modify the
key and then hash it again, it would go to a different location.
In that case you might have two entries for the same key,
or you might not be able to find a key. Either way, the
dictionary wouldn’t work correctly.

That’s why the keys have to be hashable, and why mutable types like
lists aren’t. The simplest way to get around this limitation is to
use tuples, which we will see in the next chapter.

Since dictionaries are mutable, they can’t be used as keys,
but they can be used as values.

Exercise 5[edit]

Read the documentation of the dictionary method 'setdefault'
and use it to write a more concise version of invert_dict.

If you played with the fibonacci function from
Section 6.7, you might have noticed that the bigger
the argument you provide, the longer the function takes to run.
Furthermore, the run time increases very quickly.

To understand why, consider this call graph for
fibonacci with n=4:

A call graph shows a set of function frames, with lines connecting each
frame to the frames of the functions it calls. At the top of the
graph, fibonacci with n=4 calls fibonacci with n=3 and n=2. In turn, fibonacci with n=3 calls
fibonacci with n=2 and n=1. And so on.

Count how many times fibonacci(0) and fibonacci(1) are
called. This is an inefficient solution to the problem, and it gets
worse as the argument gets bigger.

One solution is to keep track of values that have already been
computed by storing them in a dictionary. A previously computed value
that is stored for later use is called a memo[1]. Here is an
implementation of fibonacci using memos:

known = {0:0, 1:1}

def fibonacci(n):
    if n in known:
        return known[n]

    res = fibonacci(n-1) + fibonacci(n-2)
    known[n] = res
    return res

known is a dictionary that keeps track of the Fibonacci
numbers we already know. It starts with
two items: 0 maps to 0 and 1 maps to 1.

Whenever fibonacci is called, it checks known.
If the result is already there, it can return
immediately. Otherwise it has to
compute the new value, add it to the dictionary, and return it.

Exercise 6[edit]

Run this version of 'fibonacci' and the original with
a range of parameters and compare their run times.

Global variables[edit]

In the previous example, known is created outside the function,
so it belongs to the special frame called __main__.
Variables in __main__ are sometimes called global
because they can be accessed from any function. Unlike local
variables, which disappear when their function ends, global variables
persist from one function call to the next.

It is common to use global variables for flags; that is,
boolean variables that indicate (“flag”) whether a condition
is true. For example, some programs use
a flag named verbose to control the level of detail in the
output:

verbose = True

def example1():
    if verbose:
        print 'Running example1'

If you try to reassign a global variable, you might be surprised.
The following example is supposed to keep track of whether the
function has been called:

been_called = False

def example2():
    been_called = True         # WRONG

But if you run it you will see that the value of been_called
doesn’t change. The problem is that example2 creates a new local
variable named been_called. The local variable goes away when
the function ends, and has no effect on the global variable.

To reassign a global variable inside a function you have to
declare the global variable before you use it:

been_called = False

def example2():
    global been_called 
    been_called = True

The global statement tells the interpreter
something like, “In this function, when I say been_called, I
mean the global variable; don’t create a local one.”

Here’s an example that tries to update a global variable:

count = 0

def example3():
    count = count + 1          # WRONG

If you run it you get:

UnboundLocalError: local variable 'count' referenced before assignment

Python assumes that count is local, which means
that you are reading it before writing it. The solution, again,
is to declare count global.

def example3():
    global count
    count += 1

If the global value is mutable, you can modify it without
declaring it:

known = {0:0, 1:1}

def example4():
    known[2] = 1

So you can add, remove and replace elements of a global list or
dictionary, but if you want to reassign the variable, you
have to declare it:

def example5():
    global known
    known = dict()

Long integers[edit]

If you compute fibonacci(50), you get:

>>> fibonacci(50)
12586269025L

The L at the end indicates that the result is a long
integer[2], or type long.

Values with type int have a limited range;
long integers can be arbitrarily big, but as they get bigger
they consume more space and time.

The mathematical operators work on long integers, and the functions
in the math module, too, so in general any code that
works with int will also work with long.

Any time the result of a computation is too big to be represented with
an integer, Python converts the result as a long integer:

>>> 1000 * 1000
1000000
>>> 100000 * 100000
10000000000L

In the first case the result has type int; in the
second case it is long.

Exercise 7[edit]

Exponentiation of large integers is the basis of common
algorithms for public-key encryption. Read the Wikipedia
page on the RSA algorithm[3]
and write functions to encode and decode messages.

Debugging[edit]

As you work with bigger datasets it can become unwieldy to
debug by printing and checking data by hand. Here are some
suggestions for debugging large datasets:

Scale down the input:
If possible, reduce the size of the
dataset. For example if the program reads a text file, start with
just the first 10 lines, or with the smallest example you can find.
You can either edit the files themselves, or (better) modify the
program so it reads only the first n lines.
If there is an error, you can reduce n to the smallest
value that manifests the error, and then increase it gradually
as you find and correct errors.
Check summaries and types:
Instead of printing and checking the
entire dataset, consider printing summaries of the data: for example,
the number of items in a dictionary or the total of a list of numbers.
A common cause of runtime errors is a value that is not the right
type. For debugging this kind of error, it is often enough to print
the type of a value.
Write self-checks:
Sometimes you can write code to check
for errors automatically. For example, if you are computing the
average of a list of numbers, you could check that the result is
not greater than the largest element in the list or less than
the smallest. This is called a “sanity check” because it detects
results that are “insane.”

Another kind of check compares the results of two different
computations to see if they are consistent. This is called a
“consistency check.”

Pretty print the output:
Formatting debugging output
can make it easier to spot an error. We saw an example in
Section 6.9. The pprint module provides
a pprint function that displays built-in types in
a more human-readable format.

Again, time you spend building scaffolding can reduce
the time you spend debugging.

Glossary[edit]

dictionary:
A mapping from a set of keys to their
corresponding values.
key-value pair:
The representation of the mapping from
a key to a value.
item:
Another name for a key-value pair.
key:
An object that appears in a dictionary as the
first part of a key-value pair.
value:
An object that appears in a dictionary as the
second part of a key-value pair. This is more specific than
our previous use of the word “value.”
implementation:
A way of performing a computation.
hashtable:
The algorithm used to implement Python
dictionaries.
hash function:
A function used by a hashtable to compute the
location for a key.
hashable:
A type that has a hash function. Immutable
types like integers,
floats and strings are hashable; mutable types like lists and
dictionaries are not.
lookup:
A dictionary operation that takes a key and finds
the corresponding value.
reverse lookup:
A dictionary operation that takes a value and finds
one or more keys that map to it.
singleton:
A list (or other sequence) with a single element.
call graph:
A diagram that shows every frame created during
the execution of a program, with an arrow from each caller to
each callee.

histogram:
A set of counters.
memo:
A computed value stored to avoid unnecessary future
computation.
global variable:
A variable defined outside a function. Global
variables can be accessed from any function.
flag:
A boolean variable used to indicate whether a condition
is true.
declaration:
A statement like global that tells the
interpreter something about a variable.

Exercise-8[edit]

        Dictionaries have a method called 'keys' that returns the keys of the dictionary, in

no particular order, as a list.
Modify print_hist to print the keys and their values in alphabetical order.

Exercise 9[edit]

Two words are “rotate pairs” if you can rotate one of them
and get the other (see rotate_word in Exercise '8.12').

Write a program that reads a wordlist and finds all the rotate
pairs.

Exercise 10[edit]

Here’s another Puzzler from Car
Talk[4]:

This was sent in by a fellow named Dan O’Leary. He came upon a common
one-syllable, five-letter word recently that has the following unique
property. When you remove the first letter, the remaining letters form
a homophone of the original word, that is a word that sounds exactly
the same. Replace the first letter, that is, put it back and remove
the second letter and the result is yet another homophone of the
original word. And the question is, what’s the word?
Now I’m going to give you an example that doesn’t work. Let’s look at
the five-letter word, ‘wrack.’ W-R-A-C-K, you know like to ‘wrack with
pain.’ If I remove the first letter, I am left with a four-letter
word, ’R-A-C-K.’ As in, ‘Holy cow, did you see the rack on that buck!
It must have been a nine-pointer!’ It’s a perfect homophone. If you
put the ‘w’ back, and remove the ‘r,’ instead, you’re left with the
word, ‘wack,’ which is a real word, it’s just not a homophone of the
other two words.

But there is, however, at least one word that Dan and we know of,
which will yield two homophones if you remove either of the first two
letters to make two, new four-letter words. The question is, what’s
the word?


'

You can use the dictionary from Exercise '11.1' to check
whether a string is in the word list.

To check whether two words are homophones, you can use the CMU
Pronouncing Dictionary. You can download it from
'www.speech.cs.cmu.edu/cgi-bin/cmudict' or from
'thinkpython.com/code/c06d' and you can also download
'thinkpython.com/code/pronounce.py', which provides a function
named read_dictionary that reads the pronouncing dictionary and
returns a Python dictionary that maps from each word to a string that
describes its primary pronunciation.

Write a program that lists all the words that solve the Puzzler.
You can see my solution at 'thinkpython.com/code/homophone.py'.

  1. See
    wikipedia.org/wiki/Memoization
  2. In Python 3.0, type long is gone; all integers,
    even really big ones, are type int.
  3. wikipedia.org/wiki/RSA
  4. www.cartalk.com/content/puzzler/transcripts/200717

Tuples are immutable[edit]

A tuple is a sequence of values. The values can be any type, and
they are indexed by integers, so in that respect tuples are a lot
like lists. The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values:

>>> t="a", 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in
parentheses:

>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include the final
comma:

>>> t1 = ('a',)
>>> type(t1)

Without the comma, Python treats ('a') as a string in
parentheses:

>>> t2 = ('a')
>>> type(t2)

Another way to create a tuple is the built-in function tuple.
With no argument, it creates an empty tuple:

>>> t = tuple()
>>> print t
()

If the argument is a sequence (string, list or tuple), the result
is a tuple with the elements of the sequence:

>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a built-in function, you should
avoid using it as a variable name.

Most list operators also work on tuples. The bracket operator
indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

And the slice operator selects a range of elements.

>>> print t[1:3]
('b', 'c')

But if you try to modify one of the elements of the tuple, you get
an error:

>>> t[0] = 'A'
TypeError: object doesn't support item assignment

You can’t modify the elements of a tuple, but you can replace
one tuple with another:

>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')

Tuple assignment[edit]

It is often useful to swap the values of two variables.
With conventional assignments, you have to use a temporary
variable. For example, to swap a and b:

>>> temp = a
>>> a = b
>>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of
expressions. Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any
of the assignments.

The number of variables on the left and the number of
values on the right have to be the same:

>>> a, b = 1, 2, 3
ValueError: too many values to unpack

More generally, the right side can be any kind of sequence
(string, list or tuple). For example, to split an email address
into a user name and a domain, you could write:

>>> addr="[email protected]"
>>> uname, domain = addr.split('@')

The return value from split is a list with two elements;
the first element is assigned to uname, the second to
domain.

>>> print uname
monty
>>> print domain
python.org

Tuples as return values[edit]

Strictly speaking, a function can only return one value, but
if the value is a tuple, the effect is the same as returning
multiple values. For example, if you want to divide two integers
and compute the quotient and remainder, it is inefficient to
compute x/y and then x%y. It is better to compute
them both at the same time.

The built-in function divmod takes two arguments and
returns a tuple of two values, the quotient and remainder.
You can store the result as a tuple:

>>> t = divmod(7, 3)
>>> print t
(2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1

Here is an example of a function that returns a tuple:

def min_max(t):
    return min(t), max(t)

max and min are built-in functions that find
the largest and smallest elements of a sequence. min_max
computes both and returns a tuple of two values.

Variable-length argument tuples[edit]

Functions can take a variable number of arguments. A parameter
name that begins with * gathers arguments into
a tuple. For example, printall
takes any number of arguments and prints them:

def printall(*args):
    print args

The gather parameter can have any name you like, but args is
conventional. Here’s how the function works:

>>> printall(1, 2.0, '3')
(1, 2.0, '3')

You can combine the gather operator with required and positional
arguments:

def pointless(required, optional=0, *args):
    print required, optional, args

Run this function with 1, 2, 3 and 4 or more arguments and
make sure you understand what it does.

The complement of gather is scatter. If you have a
sequence of values and you want to pass it to a function
as multiple arguments, you can use the * operator.
For example, divmod takes exactly two arguments; it
doesn’t work with a tuple:

>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:

>>> divmod(*t)
(2, 1)

Exercise 1[edit]

Many of the built-in functions use
variable-length argument tuples. For example, 'max'
and 'min' can take any number of arguments:

''>>> max(1,2,3)
3
''

But 'sum' does not.

''>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
''

Write a function called 'sumall' that takes any number
of arguments and returns their sum.

Lists and tuples[edit]

zip is a built-in function that takes two or more sequences and
“zips” them into a list1 of tuples where each tuple contains one element from each
sequence.

This example zips a string and a list:

>>> s="abc"
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

The result is a list of tuples where each tuple contains
a character from the string and the corresponding element from
the list.

If the sequences are not the same length, the result has the
length of the shorter one.

>>> zip('Anne', 'Elk')
[('A', 'E'), ('n', 'l'), ('n', 'k')]

You can use tuple assignment in a for loop to traverse a list of
tuples:

t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
    print number, letter

Each time through the loop, Python selects the next tuple in
the list and assigns the elements to letter and
number. The output of this loop is:

0 a
1 b
2 c

If you combine zip, for and tuple assignment, you get a
useful idiom for traversing two (or more) sequences at the same
time. For example, has_match takes two sequences, t1 and
t2, and returns True if there is an index i
such that t1[i] == t2[i]:

def has_match(t1, t2):
    for x, y in zip(t1, t2):
        if x == y:
            return True
    return False

If you need to traverse the elements of a sequence and their
indices, you can use the built-in function enumerate:

for index, element in enumerate('abc'):
    print index, element

The output of this loop is:

0 a
1 b
2 c

Again.

Dictionaries and tuples[edit]

Dictionaries have a method called items that returns a list of
tuples, where each tuple is a key-value pair2.

>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

As you should expect from a dictionary, the items are in no
particular order.

Conversely, you can use a list of tuples to initialize
a new dictionary:

>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}

Combining dict with zip yields a concise way
to create a dictionary:

>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}

The dictionary method update also takes a list of tuples
and adds them, as key-value pairs, to an existing dictionary.

Combining items, tuple assignment and for, you
get the idiom for traversing the keys and values of a dictionary:

for key, val in d.items():
    print val, key

The output of this loop is:

0 a
2 c
1 b

Again.

It is common to use tuples as keys in dictionaries (primarily because
you can’t use lists). For example, a telephone directory might map
from last-name, first-name pairs to telephone numbers. Assuming
that we have defined last, first and number, we
could write:

directory[last,first] = number

The expression in brackets is a tuple. We could use tuple
assignment to traverse this dictionary.

for last, first in directory:
    print first, last, directory[last,first]

This loop traverses the keys in directory, which are tuples. It
assigns the elements of each tuple to last and first, then
prints the name and corresponding telephone number.

There are two ways to represent tuples in a state diagram. The more
detailed version shows the indices and elements just as they appear in
a list. For example, the tuple ('Cleese', 'John') would appear:

But in a larger diagram you might want to leave out the
details. For example, a diagram of the telephone directory might
appear:

Here the tuples are shown using Python syntax as a graphical
shorthand.

The telephone number in the diagram is the complaints line for the
BBC, so please don’t call it.

Comparing tuples[edit]

The comparison operators work with tuples and other sequences;
Python starts by comparing the first element from each
sequence. If they are equal, it goes on to the next elements,
and so on, until it finds elements that differ. Subsequent
elements are not considered (even if they are really big).

>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

The sort function works the same way. It sorts
primarily by first element, but in the case of a tie, it sorts
by second element, and so on.

This feature lends itself to a pattern called DSU for

Decorate
a sequence by building a list of tuples
with one or more sort keys preceding the elements from the sequence,
Sort
the list of tuples, and
Undecorate
by extracting the sorted elements of the sequence.

For example, suppose you have a list of words and you want to
sort them from longest to shortest:

def sort_by_length(words):
    t = []
    for word in words:
       t.append((len(word), word))

    t.sort(reverse=True)

    res = []
    for length, word in t:
        res.append(word)
    return res

The first loop builds a list of tuples, where each
tuple is a word preceded by its length.

sort compares the first element, length, first, and
only considers the second element to break ties. The keyword argument
reverse=True tells sort to go in decreasing order.

The second loop traverses the list of tuples and builds a list of
words in descending order of length.

Exercise 2[edit]

In this example, ties are broken by comparing words, so words
with the same length appear in alphabetical order. For other
applications you might want to break ties at random. Modify
this example so that words with the same length appear in
random order. Hint: see the 'random' function in the
'random' module.

Sequences of sequences[edit]

I have focused on lists of tuples, but almost all of the examples in
this chapter also work with lists of lists, tuples of tuples, and
tuples of lists. To avoid enumerating the possible combinations, it
is sometimes easier to talk about sequences of sequences.

In many contexts, the different kinds of sequences (strings, lists and
tuples) can be used interchangeably. So how and why do you choose one
over the others?

To start with the obvious, strings are more limited than other
sequences because the elements have to be characters. They are
also immutable. If you need the ability to change the characters
in a string (as opposed to creating a new string), you might
want to use a list of characters instead.

Lists are more common than tuples, mostly because they are mutable.
But there are a few cases where you might prefer tuples:

  • In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. In other contexts, you might prefer a list.
  • If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.
  • If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.

Because tuples are immutable, they don’t provide methods
like sort and reverse, which modify existing lists.
But Python provides the built-in functions sorted
and reversed, which take any sequence as a parameter
and return a new list with the same elements in a different
order.

Debugging[edit]

Lists, dictionaries and tuples are known generically as data
structures; in this chapter we are starting to see compound data
structures, like lists of tuples, and dictionaries that contain tuples
as keys and lists as values. Compound data structures are useful, but
they are prone to what I call shape errors; that is, errors
caused when a data structure has the wrong type, size or composition.
For example, if you are expecting a list with one integer and I
give you a plain old integer (not in a list), it won’t work.

To help debug these kinds of errors, I have written a module
called structshape that provides a function, also called
structshape, that takes any kind of data structure as
an argument and returns a string that summarizes its shape.
You can download it from thinkpython.com/code/structshape.py

Here’s the result for a simple list:

>>> from structshape import structshape
>>> t = [1,2,3]
>>> print structshape(t)
list of 3 int

A fancier program might write “list of 3 ints,” but it
was easier not to deal with plurals. Here’s a list of lists:

>>> t2 = [[1,2], [3,4], [5,6]]
>>> print structshape(t2)
list of 3 list of 2 int

If the elements of the list are not the same type,
structshape groups them, in order, by type:

>>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9]
>>> print structshape(t3)
list of (3 int, float, 2 str, 2 list of int, int)

Here’s a list of tuples:

>>> s="abc"
>>> lt = zip(t, s)
>>> print structshape(lt)
list of 3 tuple of (int, str)

And here’s a dictionary with 3 items that map integers to strings.

>>> d = dict(lt) 
>>> print structshape(d)
dict of 3 int->str

If you are having trouble keeping track of your data structures,
structshape can help.

Glossary[edit]

tuple:
An immutable sequence of elements.
tuple assignment:
An assignment with a sequence on the
right side and a tuple of variables on the left. The right
side is evaluated and then its elements are assigned to the
variables on the left.

gather:
The operation of assembling a variable-length
argument tuple.
scatter:
The operation of treating a sequence as a list of
arguments.
DSU:
Abbreviation of “decorate-sort-undecorate,” a
pattern that involves building a list of tuples, sorting, and
extracting part of the result.
data structure:
A collection of related values, often
organized in lists, dictionaries, tuples, etc.
shape (of a data structure):
A summary of the type,
size and composition of a data structure.

Exercises[edit]

Exercise 3[edit]

Write a function called most_frequent that takes a string and
prints the letters in decreasing order of frequency. Find text
samples from several different languages and see how letter frequency
varies between languages. Compare your results with the tables at
'wikipedia.org/wiki/Letter_frequencies'.

Exercise 4[edit]

More anagrams!

that reads a word list from a file (see Section '9.1') and
prints all the sets of words that are anagrams.
Here is an example of what the output might look like:

''['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']
['retainers', 'ternaries']
['generating', 'greatening']
['resmelts', 'smelters', 'termless']
''

Hint: you might want to build a dictionary that maps from a
set of letters to a list of words that can be spelled with those
letters. The question is, how can you represent the set of
letters in a way that can be used as a key?

  • Modify the previous program so that it prints the largest set

of anagrams first, followed by the second largest set, and so on.

  • In Scrabble a “bingo” is when you play all seven tiles in

your rack, along with a letter on the board, to form an eight-letter
word. What set of 8 letters forms the most possible bingos?
Hint: there are seven.

  • 'Two words form a “metathesis pair” if you can transform one

into the other by swapping two letters''3''; for example,
“converse” and “conserve.” Write a program that finds all of
the metathesis pairs in the dictionary. Hint: don’t test all pairs
of words, and don’t test all possible swaps.'
'You can download a solution from '''thinkpython.com/code/anagram_sets.py'''.'

Exercise 5[edit]

Here’s another Car Talk Puzzler4:

What is the longest English word, that remains a valid English word,
as you remove its letters one at a time?
Now, letters can be removed from either end, or the middle, but you
can’t rearrange any of the letters. Every time you drop a letter, you
wind up with another English word. If you do that, you’re eventually
going to wind up with one letter and that too is going to be an
English word—one that’s found in the dictionary. I want to know
what’s the longest word and how many letters does it
have?

I’m going to give you a little modest example: Sprite. Ok? You start
off with sprite, you take a letter off, one from the interior of the
word, take the r away, and we’re left with the word spite, then we
take the e off the end, we’re left with spit, we take the s off, we’re
left with pit, it, and I.

Write a program to find all words that can be reduced in this way,
and then find the longest one.

This exercise is a little more challenging than most, so here are
some suggestions:

  • You might want to write a function that takes a word and

computes a list of all the words that can be formed by removing one
letter. These are the “children” of the word.

  • Recursively, a word is reducible if any of its children

are reducible. As a base case, you can consider the empty
string reducible.

  • The wordlist I provided, 'words.txt', doesn’t

contain single letter words. So you might want to add
“I”, “a”, and the empty string.

  • To improve the performance of your program, you might want

to memoize the words that are known to be reducible.

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

Word frequency analysis[edit]

As usual, you should at least attempt the following exercises
before you read my solutions.

Exercise 1[edit]

Write a program that reads a file, breaks each line into
words, strips whitespace and punctuation from the words, and
converts them to lowercase.

Hint: The 'string' module provides strings named 'whitespace',
which contains space, tab, newline, etc., and 'punctuation' which contains the punctuation characters. Let’s see
if we can make Python swear:

>>> import string
>>> print string.punctuation
!"#$%&'()*+,-./:;<=>[email protected][]^_`{|}~

Also, you might consider using the string methods 'strip',
'replace' and 'translate'.

Exercise 2[edit]

Go to Project Gutenberg ('gutenberg.org') and download
your favorite out-of-copyright book in plain text format.

Modify your program from the previous exercise to read the book
you downloaded, skip over the header information at the beginning
of the file, and process the rest of the words as before.

Then modify the program to count the total number of words in
the book, and the number of times each word is used.

Print the number of different words used in the book. Compare
different books by different authors, written in different eras.
Which author uses the most extensive vocabulary?

Exercise 3[edit]

Modify the program from the previous exercise to print the
20 most frequently-used words in the book.

Exercise 4[edit]

Modify the previous program to read a word list (see
Section '9.1') and then print all the words in the book that
are not in the word list. How many of them are typos? How many of
them are common words that should be in the word list, and how
many of them are really obscure?

Random numbers[edit]

Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be deterministic.
Determinism is usually a good thing, since we expect the same
calculation to yield the same result. For some applications, though,
we want the computer to be unpredictable. Games are an obvious
example, but there are more.

Making a program truly nondeterministic turns out to be not so easy,
but there are ways to make it at least seem nondeterministic. One of
them is to use algorithms that generate pseudorandom numbers.
Pseudorandom numbers are not truly random because they are generated
by a deterministic computation, but just by looking at the numbers it
is all but impossible to distinguish them from random.

The random module provides functions that generate
pseudorandom numbers (which I will simply call “random” from
here on).

The function random returns a random float
between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you
call random, you get the next number in a long series. To see a
sample, run this loop:

import random

for i in range(10):
    x = random.random()
    print x

The function randint takes parameters low and
high and returns an integer between low and
high (including both).

>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9

To choose an element from a sequence at random, you can use
choice:

>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3

The random module also provides functions to generate
random values from continuous distributions including
Gaussian, exponential, gamma, and a few more.

Exercise 5[edit]

Write a function named choose_from_hist that takes
a histogram as defined in Section '11.1' and returns a
random value from the histogram, chosen with probability
in proportion to frequency. For example, for this histogram:

''>>> t = ['a', 'a', 'b']
>>> h = histogram(t)
>>> print h
{'a': 2, 'b': 1}
''

your function should '’a’' with probability '2/3' and b
with probability '1/3'.

Word histogram[edit]

Here is a program that reads a file and builds a histogram of the
words in the file:

import string

def process_file(filename):
    h = dict()
    fp = open(filename)
    for line in fp:
        process_line(line, h)
    return h

def process_line(line, h):
    line = line.replace('-', ' ')
    
    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()

        h[word] = h.get(word, 0) + 1

hist = process_file('emma.txt')

This program reads emma.txt, which contains the text of Emma by Jane Austen.

process_file loops through the lines of the file,
passing them one at a time to process_line. The histogram
h is being used as an accumulator.

process_line uses the string method replace to replace
hyphens with spaces before using split to break the line into a
list of strings. It traverses the list of words and uses strip
and lower to remove punctuation and convert to lower case. (It
is a shorthand to say that strings are “converted;” remember that
string are immutable, so methods like strip and lower
return new strings.)

Finally, process_line updates the histogram by creating a new
item or incrementing an existing one.

To count the total number of words in the file, we can add up
the frequencies in the histogram:

def total_words(h):
    return sum(h.values())

The number of different words is just the number of items in
the dictionary:

def different_words(h):
    return len(h)

Here is some code to print the results:

print 'Total number of words:', total_words(hist)
print 'Number of different words:', different_words(hist)

And the results:

Total number of words: 161073
Number of different words: 7212

Most common words[edit]

To find the most common words, we can apply the DSU pattern;
most_common takes a histogram and returns a list of
word-frequency tuples, sorted in reverse order by frequency:

def most_common(h):
    t = []
    for key, value in h.items():
        t.append((value, key))

    t.sort(reverse=True)
    return t

Here is a loop that prints the ten most common words:

t = most_common(hist)
print 'The most common words are:'
for freq, word in t[0:10]:
    print word, 't', freq

And here are the results from Emma:

The most common words are:
to      5242
the     5204
and     4897
of      4293
i       3191
a       3130
it      2529
her     2483
was     2400
she     2364

Optional parameters[edit]

We have seen built-in functions and methods that take a variable
number of arguments. It is possible to write user-defined functions
with optional arguments, too. For example, here is a function that
prints the most common words in a histogram

def print_most_common(hist, num=10)
    t = most_common(hist)
    print 'The most common words are:'
    for freq, word in t[0:num]:
        print word, 't', freq

The first parameter is required; the second is optional.
The default value of num is 10.

If you only provide one argument:

print_most_common(hist)

num gets the default value. If you provide two arguments:

print_most_common(hist, 20)

num gets the value of the argument instead. In other
words, the optional argument overrides the default value.

If a function has both required and optional parameters, all
the required parameters have to come first, followed by the
optional ones.

Dictionary subtraction[edit]

Finding the words from the book that are not in the word list
from words.txt is a problem you might recognize as set
subtraction; that is, we want to find all the words from one
set (the words in the book) that are not in another set (the
words in the list).

subtract takes dictionaries d1 and d2 and returns a
new dictionary that contains all the keys from d1 that are not
in d2. Since we don’t really care about the values, we
set them all to None.

def subtract(d1, d2):
    res = dict()
    for key in d1:
        if key not in d2:
            res[key] = None
    return res

To find the words in the book that are not in words.txt,
we can use process_file to build a histogram for
words.txt, and then subtract:

words = process_file('words.txt')
diff = subtract(hist, words)

print "The words in the book that aren't in the word list are:"
for word in diff.keys():
    print word,

Here are some of the results from Emma:

The words in the book that aren't in the word list are:
 rencontre jane's blanche woodhouses disingenuousness 
friend's venice apartment ...

Some of these words are names and possessives. Others, like
“rencontre,” are no longer in common use. But a few are common
words that should really be in the list!

Exercise 6[edit]

Python provides a data structure called 'set' that provides many
common set operations. Read the documentation at
'docs.python.org/lib/types-set.html' and write a program
that uses set subtraction to find words in the book that are not in
the word list.

Random words[edit]

To choose a random word from the histogram, the simplest algorithm
is to build a list with multiple copies of each word, according
to the observed frequency, and then choose from the list:

def random_word(h):
    t = []
    for word, freq in h.items():
        t.extend([word] * freq)

    return random.choice(t)

The expression [word] * freq creates a list with freq
copies of the string word. The extend
method is similar to append except that the argument is
a sequence.

Exercise 7[edit]

This algorithm works, but it is not very efficient; each time you
choose a random word, it rebuilds the list, which is as big as
the original book. An obvious improvement is to build the list
once and then make multiple selections, but the list is still big.

An alternative is:

  • Use 'keys' to get a list of the words in the book.
  • Build a list that contains the cumulative sum of the word

frequencies (see Exercise '10.1'). The last item
in this list is the total number of words in the book, 'n'.

  • Choose a random number from 1 to 'n'. Use a bisection search

(See Exercise '10.8') to find the index where the random
number would be inserted in the cumulative sum.

  • Use the index to find the corresponding word in the word list.

Write a program that uses this algorithm to choose a random
word from the book.

Markov analysis[edit]

If you choose words from the book at random, you can get a
sense of the vocabulary, you probably won’t get a sentence:

this the small regard harriet which knightley's it most things

A series of random words seldom makes sense because there
is no relationship between successive words. For example, in
a real sentence you would expect an article like “the” to
be followed by an adjective or a noun, and probably not a verb
or adverb.

One way to measure these kinds of relationships is Markov
analysis, which characterizes, for a given sequence of words,
the probability of the word that comes next. For example,
the song Eric, the Half a Bee begins:

Half a bee, philosophically,
Must, ipso facto, half not be.
But half the bee has got to be
Vis a vis, its entity. D’you see?

But can a bee be said to be
Or not to be an entire bee
When half the bee is not a bee
Due to some ancient injury?

In this text,
the phrase “half the” is always followed by the word “bee,”
but the phrase “the bee” might be followed by either
“has” or “is”.

The result of Markov analysis is a mapping from each prefix
(like “half the” and “the bee”) to all possible suffixes
(like “has” and “is”).

Given this mapping, you can generate a random text by
starting with any prefix and choosing at random from the
possible suffixes. Next, you can combine the end of the
prefix and the new suffix to form the next prefix, and repeat.

For example, if you start with the prefix “Half a,” then the
next word has to be “bee,” because the prefix only appears
once in the text. The next prefix is “a bee,” so the
next suffix might be “philosophically,” “be” or “due.”

In this example the length of the prefix is always two, but
you can do Markov analysis with any prefix length. The length
of the prefix is called the “order” of the analysis.

Exercise 8[edit]

Markov analysis:

  • Write a program to read a text from a file and perform Markov analysis. The result should be a dictionary that maps from prefixes to a collection of possible suffixes. The collection might be a list, tuple, or dictionary; it is up to you to make an appropriate choice. You can test your program with prefix length two, but you should write the program in a way that makes it easy to try other lengths.
  • Add a function to the previous program to generate random text based on the Markov analysis. Here is an example from Emma with prefix length 2:

He was very clever, be it sweetness or be angry, ashamed or only

amused, at such a stroke. She had never thought of Hannah till you
were never meant for me?" "I cannot make speeches, Emma:" he soon cut
it all himself.

For this example, I left the punctuation attached to the words. The result is almost syntactically correct, but not quite. Semantically, it almost makes sense, but not quite.

  • What happens if you increase the prefix length? Does the random text make more sense?
  • Once your program is working, you might want to try a mash-up: if you analyze text from two or more books, the random text you generate will blend the vocabulary and phrases from the sources in interesting ways.

Data structures[edit]

Using Markov analysis to generate random text is fun, but there is
also a point to this exercise: data structure selection. In your
solution to the previous exercises, you had to choose:

  • How to represent the prefixes.
  • How to represent the collection of possible suffixes.
  • How to represent the mapping from each prefix to the collection of possible suffixes.

Ok, the last one is the easy; the only mapping type we have
seen is a dictionary, so it is the natural choice.

For the prefixes, the most obvious options are string,
list of strings, or tuple of strings. For the suffixes,
one option is a list; another is a histogram (dictionary).

How should you choose? The first step is to think about
the operations you will need to implement for each data structure.
For the prefixes, we need to be able to remove words from
the beginning and add to the end. For example, if the current
prefix is “Half a,” and the next word is “bee,” you need
to be able to form the next prefix, “a bee.”

Your first choice might be a list, since it is easy to add
and remove elements, but we also need to be able to use the
prefixes as keys in a dictionary, so that rules out lists.
With tuples, you can’t append or remove, but you can use
the addition operator to form a new tuple:

def shift(prefix, word):
    return prefix[1:] + (word,)

shift takes a tuple of words, prefix, and a string,
word, and forms a new tuple that has all the words
in prefix except the first, and word added to
the end.

For the collection of suffixes, the operations we need to
perform include adding a new suffix (or increasing the frequency
of an existing one), and choosing a random suffix.

Adding a new suffix is equally easy for the list implementation
or the histogram. Choosing a random element from a list
is easy; choosing from a histogram is harder to do
efficiently (see Exercise 13.7).

So far we have been talking mostly about ease of implementation,
but there are other factors to consider in choosing data structures.
One is run time. Sometimes there is a theoretical reason to expect
one data structure to be faster than other; for example, I mentioned
that the in operator is faster for dictionaries than for lists,
at least when the number of elements is large.

But often you don’t know ahead of time which implementation will
be faster. One option is to implement both of them and see which
is better. This approach is called benchmarking. A practical
alternative is to choose the data structure that is
easiest to implement, and then see if it is fast enough for the
intended application. If so, there is no need to go on. If not,
there are tools, like the profile module, that can identify
the places in a program that take the most time.

The other factor to consider is storage space. For example, using a
histogram for the collection of suffixes might take less space because
you only have to store each word once, no matter how many times it
appears in the text. In some cases, saving space can also make your
program run faster, and in the extreme, your program might not run at
all if you run out of memory. But for many applications, space is a
secondary consideration after run time.

One final thought: in this discussion, I have implied that
we should use one data structure for both analysis and generation. But
since these are separate phases, it would also be possible to use one
structure for analysis and then convert to another structure for
generation. This would be a net win if the time saved during
generation exceeded the time spent in conversion.

Debugging[edit]

When you are debugging a program, and especially if you are
working on a hard bug, there are four things to try:

reading:
Examine your code, read it back to yourself, and
check that it says what you meant to say.
running:
Experiment by making changes and running different
versions. Often if you display the right thing at the right place
in the program, the problem becomes obvious, but sometimes you have to
spend some time to build scaffolding.
ruminating:
Take some time to think! What kind of error
is it: syntax, runtime, semantic? What information can you get from
the error messages, or from the output of the program? What kind of
error could cause the problem you’re seeing? What did you change
last, before the problem appeared?
retreating:
At some point, the best thing to do is back
off, undoing recent changes, until you get back to a program that
works and that you understand. Then you can starting rebuilding.

Beginning programmers sometimes get stuck on one of these activities
and forget the others. Each activity comes with its own failure
mode.

For example, reading your code might help if the problem is a
typographical error, but not if the problem is a conceptual
misunderstanding. If you don’t understand what your program does, you
can read it 100 times and never see the error, because the error is in
your head.

Running experiments can help, especially if you run small, simple
tests. But if you run experiments without thinking or reading your
code, you might fall into a pattern I call “random walk programming,”
which is the process of making random changes until the program
does the right thing. Needless to say, random walk programming
can take a long time.

You have to take time to think. Debugging is like an
experimental science. You should have at least one hypothesis about
what the problem is. If there are two or more possibilities, try to
think of a test that would eliminate one of them.

Taking a break helps with the thinking. So does talking.
If you explain the problem to someone else (or even yourself), you
will sometimes find the answer before you finish asking the question.

But even the best debugging techniques will fail if there are too many
errors, or if the code you are trying to fix is too big and
complicated. Sometimes the best option is to retreat, simplifying the
program until you get to something that works and that you
understand.

Beginning programmers are often reluctant to retreat because
they can’t stand to delete a line of code (even if it’s wrong).
If it makes you feel better, copy your program into another file
before you start stripping it down. Then you can paste the pieces
back in a little bit at a time.

Finding a hard bug requires reading, running, ruminating, and
sometimes retreating. If you get stuck on one of these activities,
try the others.

Glossary[edit]

deterministic:
Pertaining to a program that does the same
thing each time it runs, given the same inputs.
pseudorandom:
Pertaining to a sequence of numbers that appear
to be random, but are generated by a deterministic program.
default value:
The value given to an optional parameter if no
argument is provided.
override:
To replace a default value with an argument.
benchmarking:
The process of choosing between data structures
by implementing alternatives and testing them on a sample of the
possible inputs.

Exercises[edit]

Exercise 9[edit]

The “rank” of a word is its position in a list of words
sorted by frequency: the most common word has rank 1, the
second most common has rank 2, etc.

Zipf’s law describes a relationship between the ranks and frequencies
of words in natural languages1. Specifically, it
predicts that the frequency, 'f', of the word with rank 'r' is:


where 's' and 'c' are parameters that depend on the language and the
text. If you take the logarithm of both sides of this equation, you
get:

log'f = 'log'c − s 'log'r 


So if you plot 'log'f' versus 'log'r', you should get
a straight line with slope ''s' and intercept 'log'c'.

Write a program that reads a text from a file, counts
word frequencies, and prints one line
for each word, in descending order of frequency, with
'log'f' and 'log'r'. Use the graphing program of your
choice to plot the results and check whether they form
a straight line. Can you estimate the value of 's'?

Persistence[edit]

Most of the programs we have seen so far are transient in the
sense that they run for a short time and produce some output,
but when they end, their data disappears. If you run the program
again, it starts with a clean slate.

Other programs are persistent: they run for a long time
(or all the time); they keep at least some of their data
in permanent storage (a hard drive, for example); and
if they shut down and restart, they pick up where they left off.

Examples of persistent programs are operating systems, which
run pretty much whenever a computer is on, and web servers,
which run all the time, waiting for requests to come in on
the network.

One of the simplest ways for programs to maintain their data
is by reading and writing text files. We have already seen
programs that read text files; in this chapters we will see programs
that write them.

An alternative is to store the state of the program in a database.
In this chapter I will present a simple database and a module,
pickle, that makes it easy to store program data.

Reading and writing[edit]

A text file is a sequence of characters stored on a permanent
medium like a hard drive, flash memory, or CD-ROM. We saw how
to open and read a file in Section 9.1.

To write a file, you have to open it with mode
'w' as a second parameter:

>>> fout = open('output.txt', 'w')
>>> print fout

If the file already exists, opening it in write mode clears out
the old data and starts fresh, so be careful!
If the file doesn’t exist, a new one is created.

The write method puts data into the file.

>>> line1 = "This here's the wattle,n"
>>> fout.write(line1)

Again, the file object keeps track of where it is, so if
you call write again, it adds the new data to the end.

>>> line2 = "the emblem of our land.n"
>>> fout.write(line2)

When you are done writing, you have to close the file.

>>> fout.close()

Format operator[edit]

The argument of write has to be a string, so if we want
to put other values in a file, we have to convert them to
strings. The easiest way to do that is with str:

>>> x = 52
>>> f.write(str(x))

An alternative is to use the format operator, %. When
applied to integers, % is the modulus operator. But
when the first operand is a string, % is the format operator.

The first operand is the format string, and the second operand
is a tuple of expressions. The result is a string that contains
the values of the expressions, formatted according to the format
string.

As an example, the format sequence '%d' means that
the first expression in the tuple should be formatted as an
integer (d stands for “decimal”):

>>> camels = 42
>>> '%d' % camels
'42'

The result is the string '42', which is not to be confused
with the integer value 42.

A format sequence can appear anywhere in the format string,
so you can embed a value in a sentence:

>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'

The format sequence '%g' formats the next element in the tuple
as a floating-point number (don’t ask why), and '%s' formats
the next item as a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number
of format sequences in the string. Also, the types of the
elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation

In the first example, there aren’t enough elements; in the
second, the element is the wrong type.

The format operator is powerful but difficult to use. You can
read more about it at docs.python.org/lib/typesseq-strings.html.

Filenames and paths[edit]

Files are organized into directories (also called “folders”).
Every running program has a “current directory,” which is the
default directory for most operations.
For example, when you open a file for reading, Python looks for it in the
current directory.

The os module provides functions for working with files and
directories (“os” stands for “operating system”). os.getcwd
returns the name of the current directory:

>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale

cwd stands for “current working directory.” The result in
this example is /home/dinsdale, which is the home directory of a
user named dinsdale.

A string like cwd that identifies a file is called a path.
A relative path starts from the current directory;
an absolute path starts from the topmost directory in the
file system.

The paths we have seen so far are simple filenames, so they are
relative to the current directory. To find the absolute path to
a file, you can use os.path.abspath:

>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'

os.path.exists checks
whether a file or directory exists:

>>> os.path.exists('memo.txt')
True

If it exists, os.path.isdir checks whether it’s a directory:

>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True

Similarly, os.path.isfile checks whether it’s a file.

os.listdir returns a list of the files (and other directories)
in the given directory:

>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']

To demonstrate these functions, the following example
“walks” through a directory, prints
the names of all the files, and calls itself recursively on
all the directories.

def walk(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)

        if os.path.isfile(path):
            print path
        else:
            walk(path)

os.path.join takes a directory and a file name and joins
them into a complete path.

Exercise 1[edit]

Modify 'walk' so that instead of printing the names of
the files, it returns a list of names.

Exercise 2  

The 'os' module provides a function called 'walk'
that is similar to this one but more versatile. Read
the documentation and use it to print the names of the
files in a given directory and its subdirectories.

Catching exceptions[edit]

A lot of things can go wrong when you try to read and write
files. If you try to open a file that doesn’t exist, you get an
IOError:

>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'

If you don’t have permission to access a file:

>>> fout = open('/etc/passwd', 'w')
IOError: [Errno 13] Permission denied: '/etc/passwd'

And if you try to open a directory for reading, you get

>>> fin = open('/home')
IOError: [Errno 21] Is a directory

To avoid these errors, you could use functions like os.path.exists
and os.path.isfile, but it would take a lot of time and code
to check all the possibilities (if “Errno 21” is any
indication, there are at least 21 things that can go wrong).

It is better to go ahead and try, and deal with problems if they
happen, which is exactly what the try statement does. The
syntax is similar to an if statement:

try:    
    fin = open('bad_file')
    for line in fin:
        print line
    fin.close()
except:
    print 'Something went wrong.'

Python starts by executing the try clause. If all goes
well, it skips the except clause and proceeds. If an
exception occurs, it jumps out of the try clause and
executes the except clause.

Handling an exception with a try statement is called catching an exception. In this example, the except clause
prints an error message that is not very helpful. In general,
catching an exception gives you a chance to fix the problem, or try
again, or at least end the program gracefully.

Databases[edit]

A database is a file that is organized for storing data.
Most databases are organized like a dictionary in the sense
that they map from keys to values. The biggest difference
is that the database is on disk (or other permanent storage),
so it persists after the program ends.

The module anydbm provides an interface for creating
and updating database files. As an example, I’ll create a database
that contains captions for image files.

Opening a database is similar
to opening other files:

>>> import anydbm
>>> db = anydbm.open('captions.db', 'c')

The mode 'c' means that the database should be created if
it doesn’t already exist. The result is a database object
that can be used (for most operations) like a dictionary.
If you create a new item, anydbm updates the database file.

>>> db['cleese.png'] = 'Photo of John Cleese.'

When you access one of the items, anydbm reads the file:

>>> print db['cleese.png']
Photo of John Cleese.

If you make another assignment to an existing key, anydbm replaces
the old value:

>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'
>>> print db['cleese.png']
Photo of John Cleese doing a silly walk.

Many dictionary methods, like keys and items, also
work with database objects. So does iteration with a for
statement.

for key in db:
     print key

As with other files, you should close the database when you are
done:

>>> db.close()

Pickling[edit]

A limitation of anydbm is that the keys and values have
to be strings. If you try to use any other type, you get an
error.

The pickle module can help. It translates
almost any type of object into a string suitable for storage in a
database, and then translates strings back into objects.

pickle.dumps takes an object as a parameter and returns
a string representation (dumps is short for “dump string”):

>>> import pickle
>>> t = [1, 2, 3]
>>> pickle.dumps(t)
'(lp0nI1naI2naI3na.'

The format isn’t obvious to human readers; it is meant to be
easy for pickle to interpret. pickle.loads
(“load string”) reconstitutes the object:

>>> t1 = [1, 2, 3]
>>> s = pickle.dumps(t1)
>>> t2 = pickle.loads(s)
>>> print t2
[1, 2, 3]

Although the new object has the same value as the old, it is
not (in general) the same object:

>>> t == t2
True
>>> t is t2
False

In other words, pickling and then unpickling has the same effect
as copying the object.

You can use pickle to store non-strings in a database.
In fact, this combination is so common that it has been
encapsulated in a module called shelve.

Exercise 3  

If you did Exercise '12.4', modify your solution so that
it creates a database that maps from each word in the list to
a list of words that use the same set of letters.

Write a different program that opens the database and prints
the contents in a human-readable format.

Most operating systems provide a command-line interface,
also known as a shell. Shells usually provide commands
to navigate the file system and launch applications. For
example, in Unix, you can change directories with cd,
display the contents of a directory with ls, and launch
a web browser by typing (for example) Firefox.

Any program that you can launch from the shell can also be
launched from Python using a pipe. A pipe is an object
that represents a running process.

For example, the Unix command ls -l normally displays the
contents of the current directory (in long format). You can
launch ls with os.popen:

>>> cmd = 'ls -l'
>>> fp = os.popen(cmd)

The argument is a string that contains a shell command. The
return value is a file pointer that behaves just like an open
file. You can read the output from the ls process one
line at a time with readline or get the whole thing at
once with read:

>>> res = fp.read()

When you are done, you close the pipe like a file:

>>> stat = fp.close()
>>> print stat
None

The return value is the final status of the ls process;
None means that it ended normally (with no errors).

A common use of pipes is to read a compressed file incrementally;
that is, without uncompressing the whole thing at once. The
following function takes the name of a compressed file as a
parameter and returns a pipe that uses gzip to decompress
the contents:

def open_gzip(filename):
    cmd = 'gunzip -c ' + filename
    fp = os.popen(cmd)
    return fp

If you read lines from fp one at a time, you never have
to store the uncompressed file in memory or on disk.

Writing modules[edit]

Any file that contains Python code can be imported as a module.
For example, suppose you have a file named wc.py with the following
code:

def linecount(filename):
    count = 0
    for line in open(filename):
        count += 1
    return count

print linecount('wc.py')

If you run this program, it reads itself and prints the number
of lines in the file, which is 7.
You can also import it like this:

>>> import wc
7

Now you have a module object wc:

>>> print wc

That provides a function called linecount:

>>> wc.linecount('wc.py')
7

So that’s how you write modules in Python.

The only problem with this example is that when you import
the module it executes the test code at the bottom. Normally
when you import a module, it defines new functions but it
doesn’t execute them.

Programs that will be imported as modules often
use the following idiom:

if __name__ == '__main__':
    print linecount('wc.py')

__name__ is a built-in variable that is set when the
program starts. If the program is running as a script,
__name__ has the value __main__; in that
case, the test code is executed. Otherwise,
if the module is being imported, the test code is skipped.

Exercise 4  

Type this example into a file named 'wc.py' and run
it as a script. Then run the Python interpreter and
'import wc'. What is the value of __name__
when the module is being imported?
Warning: If you import a module that has already been imported,
Python does nothing. It does not re-read the file, even if it has
changed.

If you want to reload a module, you can use the built-in function
'reload', but it can be tricky, so the safest thing to do is
restart the interpreter and then import the module again.

Debugging[edit]

When you are reading and writing files, you might run into problems
with whitespace. These errors can be hard to debug because spaces,
tabs and newlines are normally invisible:

>>> s="1 2t 3n 4"
>>> print s
1 2  3
 4

The built-in function repr can help. It takes any object as an
argument and returns a string representation of the object. For
strings, it represents whitespace
characters with backslash sequences:

>>> print repr(s)
'1 2t 3n 4'

This can be helpful for debugging.

One other problem you might run into is that different systems
use different characters to indicate the end of a line. Some
systems use a newline, represented n. Others use
a return character, represented r. Some use both.
If you move files between different systems, these inconsistencies
might cause problems.

For most systems, there are applications to convert from one
format to another. You can find them (and read more about this
issue) at wikipedia.org/wiki/Newline. Or, of course, you
could write one yourself.

Glossary[edit]

persistent:
Pertaining to a program that runs indefinitely
and keeps at least some of its data in permanent storage.
format operator:
An operator, %, that takes a format
string and a tuple and generates a string that includes
the elements of the tuple formatted as specified by the format string.
format string:
A string, used with the format operator, that
contains format sequences.
format sequence:
A sequence of characters in a format string,
like %d, that specifies how a value should be formatted.
text file:
A sequence of characters stored in permanent
storage like a hard drive.
directory:
A named collection of files, also called a folder.
path:
A string that identifies a file.
relative path:
A path that starts from the current directory.
absolute path:
A path that starts from the topmost directory
in the file system.
catch:
To prevent an exception from terminating
a program using the try
and except statements.
database:
A file whose contents are organized like a dictionary
with keys that correspond to values.

Exercises[edit]

Exercise 5  

The 'urllib' module provides methods for manipulating URLs
and downloading information from the web. The following example
downloads and prints a secret message from 'thinkpython.com':

import urllib

conn = urllib.urlopen('http://thinkpython.com/secret.html')
for line in conn.fp:
    print line.strip()

Run this code and follow the instructions you see there.

Exercise 6  

In a large collection of MP3 files, there may be more than one
copy of the same song, stored in different directories or with
different file names. The goal of this exercise is to search for
these duplicates.

  • Write a program that searches a directory and all of its

subdirectories, recursively, and returns a list of complete paths
for all files with a given suffix (like '.mp3').
Hint: 'os.path' provides several useful functions for
manipulating file and path names.

  • To recognize duplicates, you can use a hash function that

reads the file and generates a short summary
of the contents. For example,
MD5 (Message-Digest algorithm 5) takes an arbitrarily-long
“message” and returns a 128-bit “checksum.” The probability
is very small that two files with different contents will
return the same checksum.
You can read about MD5 at 'wikipedia.org/wiki/Md5'. On
a Unix system you can use the program 'md5sum' and a pipe to
compute checksums from Python.

Exercise 7  


'

The Internet Movie Database (IMDb) is an online collection of
information about movies. Their database is available
in plain text format, so it is reasonably easy to read from
Python. For this exercise, the files you need
are 'actors.list.gz' and 'actresses.list.gz'; you
can download them from 'www.imdb.com/interfaces#plain'.


'

I have written a program that parses these files and
splits them into actor names, movie titles, etc. You can
download it from 'thinkpython.com/code/imdb.py'.

If you run 'imdb.py' as a script, it reads 'actors.list.gz'
and prints one actor-movie pair per line. Or, if you 'import
imdb
' you can use the function process_file to, well,
process the file. The arguments are a filename, a function
object and an optional number of lines to process. Here is
an example:

''import imdb

def print_info(actor, date, title, role):
    print actor, date, title, role

imdb.process_file('actors.list.gz', print_info)
''

When you call process_file, it opens 'filename', reads the
contents, and calls print_info once for each line in the file.
print_info takes an actor, date, movie title and role as
arguments and prints them.

  • Write a program that reads 'actors.list.gz' and 'actresses.list.gz' and uses 'shelve' to build a database

that maps from each actor to a list of his or her films.

  • Two actors are “costars” if they have been in at least one

movie together. Process the database you built in the previous step
and build a second database that maps from each actor to a list of
his or her costars.

  • Write a program that can play the “Six Degrees of Kevin

Bacon,” which you can read about at
'wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon'. This
problem is challenging because it requires you to find the shortest
path in a graph. You can read about shortest path algorithms
at 'wikipedia.org/wiki/Shortest_path_problem'.

User-defined types[edit]

We have used many of Python’s built-in types; now we are going
to define a new type. As an example, we will create a type
called Point that represents a point in two-dimensional
space.

In mathematical notation, points are often written in
parentheses with a comma separating the coordinates. For example,
(0, 0) represents the origin, and (x, y) represents the
point x units to the right and y units up from the origin.

There are several ways we might represent points in Python:

  • We could store the coordinates separately in two variables, x and y.
  • We could store the coordinates as elements in a list or tuple.
  • We could create a new type to represent points as objects.

Creating a new type
is (a little) more complicated than the other options, but
it has advantages that will be apparent soon.

A user-defined type is also called a class.
A class definition looks like this:

class Point(object):
    """represents a point in 2-D space"""

This header indicates that the new class is a Point,
which is a kind of object, which is a built-in
type.

The body is a docstring that explains what the class is for.
You can define variables and functions inside a class definition,
but we will get back to that later.

Defining a class named Point creates a class object.

>>> print Point

Because Point is defined at the top level, its “full
name” is __main__.Point.

The class object is like a factory for creating objects. To create a
Point, you call Point as if it were a function.

>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>

The return value is a reference to a Point object, which we
assign to blank.
Creating a new object is called
instantiation, and the object is an instance of
the class.

When you print an instance, Python tells you what class it
belongs to and where it is stored in memory (the prefix
0x means that the following number is in hexadecimal).

Attributes[edit]

You can assign values to an instance using dot notation:

>>> blank.x = 3.0
>>> blank.y = 4.0

This syntax is similar to the syntax for selecting a variable from a
module, such as math.pi or string.whitespace. In this case,
though, we are assigning values to named elements of an object.
These elements are called attributes.

As a noun, “AT-trib-ute” is pronounced with emphasis on the first
syllable, as opposed to “a-TRIB-ute,” which is a verb.

The following diagram shows the result of these assignments.
A state diagram that shows an object and its attributes is
called an object diagram:

File:Book022.png

The variable blank refers to a Point object, which
contains two attributes. Each attribute refers to a
floating-point number.

You can read the value of an attribute using the same syntax:

>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0

The expression blank.x means, “Go to the object blank
refers to and get the value of x.” In this case, we assign that
value to a variable named x. There is no conflict between
the variable x and the attribute x.

You can use dot notation as part of any expression. For example:

>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> distance = math.sqrt(blank.x**2 + blank.y**2)
>>> print distance
5.0

You can pass an instance as an argument in the usual way.
For example:

def print_point(p):
    print '(%g, %g)' % (p.x, p.y)

print_point takes a point as an argument and displays it in
mathematical notation. To invoke it, you can pass blank as
an argument:

>>> print_point(blank)
(3.0, 4.0)

Inside the function, p is an alias for blank, so if
the function modifies p, blank changes.

Exercise 1[edit]

Write a function called 'distance' that it takes two Points
as arguments and returns the distance between them.

Rectangles[edit]

Sometimes it is obvious what the attributes of an object should be,
but other times you have to make decisions. For example, imagine you
are designing a class to represent rectangles. What attributes would
you use to specify the location and size of a rectangle? You can
ignore angle; to keep things simple, assume that the rectangle is
either vertical or horizontal.

There are at least two possibilities:

  • You could specify one corner of the rectangle (or the center), the width, and the height.
  • You could specify two opposing corners.

At this point it is hard to say whether either is better than
the other, so we’ll implement the first one, just as an example.

Here is the class definition:

class Rectangle(object):
    """represent a rectangle. 
       attributes: width, height, corner.
    """

The docstring lists the attributes: width and
height are numbers; corner is a Point object that
specifies the lower-left corner.

To represent a rectangle, you have to instantiate a Rectangle
object and assign values to the attributes:

box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0

The expression box.corner.x means,
“Go to the object box refers to and select the attribute named
corner; then go to that object and select the attribute named
x.”

The figure shows the state of this object:

File:Book023.png
An object that is an attribute of another object is embedded.

Instances as return values[edit]

Functions can return instances. For example, find_center
takes a Rectangle as an argument and returns a Point
that contains the coordinates of the center of the Rectangle:

def find_center(box):
    p = Point()
    p.x = box.corner.x + box.width/2.0
    p.y = box.corner.y + box.height/2.0
    return p

Here is an example that passes box as an argument and assigns
the resulting Point to center:

>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)

Objects are mutable[edit]

You can change the state of an object by making an assignment to one of
its attributes. For example, to change the size of a rectangle
without changing its position, you can modify the values of width and height:

box.width = box.width + 50
box.height = box.height + 100

You can also write functions that modify objects. For example,
grow_rectangle takes a Rectangle object and two numbers,
dwidth and dheight, and adds the numbers to the
width and height of the rectangle:

def grow_rectangle(rect, dwidth, dheight) :
    rect.width += dwidth
    rect.height += dheight

Here is an example that demonstrates the effect:

>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0

Inside the function, rect is an
alias for box, so if the function modifies rect,
box changes.

Exercise 2[edit]

Write a function named move_rectangle that takes
a Rectangle and two numbers named 'dx' and 'dy'. It
should change the location of the rectangle by adding 'dx'
to the 'x' coordinate of 'corner' and adding 'dy'
to the 'y' coordinate of 'corner'.

Copying[edit]

Aliasing can make a program difficult to read because changes
in one place might have unexpected effects in another place.
It is hard to keep track of all the variables that might refer
to a given object.

Copying an object is often an alternative to aliasing.
The copy module contains a function called copy that
can duplicate any object:

>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0

>>> import copy
>>> p2 = copy.copy(p1)

p1 and p2 contain the same data, but they are
not the same Point.

>>> print_point(p1)
(3.0, 4.0)
>>> print_point(p2)
(3.0, 4.0)
>>> p1 is p2
False
>>> p1 == p2
False

The is operator indicates that p1 and p2 are not the
same object, which is what we expected. But you might have expected
== to yield True because these points contain the same
data. In that case, you will be disappointed to learn that for
instances, the default behavior of the == operator is the same
as the is operator; it checks object identity, not object
equivalence. This behavior can be changed—we’ll see how later.

If you use copy.copy to duplicate a Rectangle, you will find
that it copies the Rectangle object but not the embedded Point.

>>> box2 = copy.copy(box)
>>> box2 is box
False
>>> box2.corner is box.corner
True

Here is what the object diagram looks like:

This operation is called a shallow copy because it copies the
object and any references it contains, but not the embedded objects.

For most applications, this is not what you want. In this example,
invoking grow_rectangle on one of the Rectangles would not
affect the other, but invoking move_rectangle on either would
affect both! This behavior is confusing and error-prone.

Fortunately, the copy module contains a method named deepcopy that copies not only the object but also
the objects it refers to, and the objects they refer to,
and so on.
You will not be surprised to learn that this operation is
called a deep copy.

>>> box3 = copy.deepcopy(box)
>>> box3 is box
False
>>> box3.corner is box.corner
False

box3 and box are completely separate objects.

Exercise 3[edit]

Write a version of move_rectangle that creates and
returns a new Rectangle instead of modifying the old one.

Debugging[edit]

When you start working with objects, you are likely to encounter
some new exceptions. If you try to access an attribute
that doesn’t exist, you get an AttributeError:

>>> p = Point()
>>> print p.z
AttributeError: Point instance has no attribute 'z'

If you are not sure what type an object is, you can ask:

>>> type(p)

If you are not sure whether an object has a particular attribute,
you can use the built-in function hasattr:

>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False

The first argument can be any object; the second argument is a string that contains the name of the attribute.

Glossary[edit]

class:
A user-defined type. A class definition creates a new
class object.
class object:
An object that contains information about a
user-defined type. The class object can be used to create instances
of the type.
instance:
An object that belongs to a class.
attribute:
One of the named values associated with an object.

embedded (object):
An object that is stored as an attribute
of another object.

shallow copy:
To copy the contents of an object, including
any references to embedded objects;
implemented by the copy function in the copy module.
deep copy:
To copy the contents of an object as well as any
embedded objects, and any objects embedded in them, and so on;
implemented by the deepcopy function in the copy module.
object diagram:
A diagram that shows objects, their
attributes, and the values of the attributes.

Exercises[edit]

Exercise 4[edit]

World.py'', which is part of Swampy (see Chapter '4'),
contains a class definition for a user-defined type called
'World'. If you run this code:

''from World import *
world = World()
wait_for_user()
''

A window should appear with a title bar and an empty square.
In this exercise we will use this window to draw Points,
Rectangles and other shapes.
Add the following lines before
wait_for_user and run the program again

''canvas = world.ca(width=500, height=500, background='white')
bbox = [[-150,-100], [150, 100]]
canvas.rectangle(bbox, outline="black", width=2, fill="green4")
''

You should see a green rectangle with a black outline.
The first line creates a Canvas, which appears in the window
as a white square. The Canvas object provides methods like
'rectangle' for drawing various shapes.

bbox'' is a list of lists that represents the “bounding box”
of the rectangle. The first pair of coordinates is the lower-left
corner of the rectangle; the second pair is the upper-right corner.

You can draw a circle like this:

''canvas.circle([-25,0], 70, outline=None, fill="red")
''

The first parameter is the coordinate pair for the center of the
circle; the second parameter is the radius.

If you add this line to the program,
the result should resemble the national flag of Bangladesh
(see 'wikipedia.org/wiki/Gallery_of_sovereign-state_flags').

  • Write a function called draw_rectangle that takes a

Canvas and a Rectangle as arguments and draws a
representation of the Rectangle on the Canvas.

  • Add an attribute named 'color' to your Rectangle objects and

modify draw_rectangle so that it uses the color attribute as
the fill color.

  • Write a function called draw_point that takes a

Canvas and a Point as arguments and draws a
representation of the Point on the Canvas.

  • Define a new class called Circle with appropriate attributes and

instantiate a few Circle objects. Write a function called
draw_circle that draws circles on the canvas.

Hint: you can draw a polygon like this:

''points = [[-150,-100], [150, 100], [150, -100]]
canvas.polygon(points, fill="blue")
''

I have written a small program that lists the available colors;
you can download it from 'thinkpython.com/code/color_list.py'.

As another example of a user-defined type, we'll define a class called
Time that records the time of day. The class definition looks
like this:

class Time(object):
  """represents the time of day.
    attributes: hour, minute, second"""

We can create a new Time object and assign
attributes for hours, minutes, and seconds:

time = Time()
time.hour = 11
time.minute = 59
time.second = 30

The state diagram for the Time object looks like this:

Exercise 1[edit]

Write a function called print_time that takes a
Time object and prints it in the form hour:minute:second.

Hint: the format sequence %.2d prints an integer using
at least two digits, including a leading zero if necessary.

Exercise 2[edit]

Write a boolean function called is_after that
takes two Time objects, t1 and t2, and
returns True if t1 follows t2
chronologically and False otherwise.

Challenge: don't use an if statement.

Pure functions[edit]

In the next few sections, we’ll write two functions that add time
values. They demonstrate two kinds of functions: pure functions and
modifiers. They also demonstrate a development plan I’ll call prototype and patch, which is a way of tackling a complex problem
by starting with a simple prototype and incrementally dealing with the
complications.

Here is a simple prototype of add_time:

def add_time(t1, t2):
  sum = Time()
  sum.hour = t1.hour + t2.hour
  sum.minute = t1.minute + t2.minute
  sum.second = t1.second + t2.second
  return sum

The function creates a new Time object, initializes its
attributes, and returns a reference to the new object. This is called
a pure function because it does not modify any of the objects
passed to it as arguments and it has no effect,
like displaying a value or getting user input,
other than returning a value.

To test this function, I’ll create two Time objects: start
contains the start time of a movie, like Monty Python and the
Holy Grail, and duration contains the run time of the movie,
which is one hour 35 minutes.

add_time figures out when the movie will be done.

>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 0

>>> duration = Time()
>>> duration.hour = 1
>>> duration.minute = 35
>>> duration.second = 0

>>> done = add_time(start, duration)
>>> print_time(done)
10:80:00

The result, 10:80:00 might not be what you were hoping
for. The problem is that this function does not deal with cases where the
number of seconds or minutes adds up to more than sixty. When that
happens, we have to “carry” the extra seconds into the minute column
or the extra minutes into the hour column.

Here’s an improved version:

def add_time(t1, t2):
  sum = Time()
  sum.hour = t1.hour + t2.hour
  sum.minute = t1.minute + t2.minute
  sum.second = t1.second + t2.second

  if sum.second >= 60:
    sum.second -= 60
    sum.minute += 1

  if sum.minute >= 60:
    sum.minute -= 60
    sum.hour += 1

  return sum

Although this function is correct, it is starting to get big.
We will see a shorter alternative later.

Modifiers[edit]

Sometimes it is useful for a function to modify the objects it gets as
parameters. In that case, the changes are visible to the caller.
Functions that work this way are called modifiers.

increment, which adds a given number of seconds to a Time
object, can be written naturally as a
modifier. Here is a rough draft:

def increment(time, seconds):
  time.second += seconds

  if time.second >= 60:
    time.second -= 60
    time.minute += 1

  if time.minute >= 60:
    time.minute -= 60
    time.hour += 1

The first line performs the basic operation; the remainder deals
with the special cases we saw before.

Is this function correct? What happens if the parameter seconds
is much greater than sixty?

In that case, it is not enough to carry
once; we have to keep doing it until time.second is less than sixty.
One solution is to replace the if statements with while
statements. That would make the function correct, but not
very efficient.

Exercise 3  

Write a correct version of 'increment' that
doesn’t contain any loops.

Anything that can be done with modifiers can also be done with pure
functions. In fact, some programming languages only allow pure
functions. There is some evidence that programs that use pure
functions are faster to develop and less error-prone than programs
that use modifiers. But modifiers are convenient at times,
and functional programs tend to be less efficient.

In general, I recommend that you write pure functions whenever it is
reasonable and resort to modifiers only if there is a compelling
advantage. This approach might be called a functional
programming style.

Exercise 4  

Write a “pure” version of 'increment' that creates and returns
a new Time object rather than modifying the parameter.

Prototyping versus planning[edit]

The development plan I am demonstrating is called “prototype and
patch.” For each function, I wrote a prototype that performed the
basic calculation and then tested it, patching errors along the
way.

This approach can be effective, especially if you don’t yet have a
deep understanding of the problem. But incremental corrections can
generate code that is unnecessarily complicated—since it deals with
many special cases—and unreliable—since it is hard to know if you
have found all the errors.

An alternative is planned development, in which high-level
insight into the problem can make the programming much easier. In
this case, the insight is that a Time object is really a three-digit
number in base 60 (see wikipedia.org/wiki/Sexagesimal)! The
second attribute is the “ones column,” the minute
attribute is the “sixties column,” and the hour attribute is
the “thirty-six hundreds column.”

When we wrote add_time and increment, we were effectively
doing addition in base 60, which is why we had to carry from one
column to the next.

This observation suggests another approach to the whole problem—we
can convert Time objects to integers and take advantage of the fact
that the computer knows how to do integer arithmetic.

Here is a function that converts Times to integers:

def time_to_int(time):
  minutes = time.hour * 60 + time.minute
  seconds = minutes * 60 + time.second
  return seconds

And here is the function that converts integers to Times
(recall that divmod divides the first argument by the second
and returns the quotient and remainder as a tuple).

def int_to_time(seconds):
  time = Time()
  minutes, time.second = divmod(seconds, 60)
  time.hour, time.minute = divmod(minutes, 60)
  return time

You might have to think a bit, and run some tests, to convince
yourself that these functions are correct. One way to test them is to
check that time_to_int(int_to_time(x)) == x for many values of
x. This is an example of a consistency check.

Once you are convinced they are correct, you can use them to
rewrite add_time:

def add_time(t1, t2):
  seconds = time_to_int(t1) + time_to_int(t2)
  return int_to_time(seconds)

This version is shorter than the original, and easier to verify.

Exercise 5  

Rewrite 'increment' using time_to_int and int_to_time.

In some ways, converting from base 60 to base 10 and back is harder
than just dealing with times. Base conversion is more abstract; our
intuition for dealing with time values is better.

But if we have the insight to treat times as base 60 numbers and make
the investment of writing the conversion functions (time_to_int
and int_to_time), we get a program that is shorter, easier to
read and debug, and more reliable.

It is also easier to add features later. For example, imagine
subtracting two Times to find the duration between them. The
naïve approach would be to implement subtraction with borrowing.
Using the conversion functions would be easier and more likely to be
correct.

Ironically, sometimes making a problem harder (or more general) makes it
easier (because there are fewer special cases and fewer opportunities
for error).

Debugging[edit]

A Time object is well-formed if the values of minutes and seconds are between 0 and 60 (including 0 but not 60) and if
hours is positive. hours and minutes should be
integral values, but we might allow seconds to have a
fraction part.

These kind of requirements are called invariants because
they should always be true. To put it a different way, if they
are not true, then something has gone wrong.

Writing code to check your invariants can help you detect errors
and find their causes. For example, you might have a function
like valid_time that takes a Time object and returns
False if it violates an invariant:

def valid_time(time):
  if time.hours < 0 or time.minutes < 0 or time.seconds < 0:
    return False
  if time.minutes >= 60 or time.seconds >= 60:
    return False
  return True

Then at the beginning of each function you could check the
arguments to make sure they are valid:

def add_time(t1, t2):
  if not valid_time(t1) or not valid_time(t2):
    raise ValueError, 'invalid Time object in add_time'
  seconds = time_to_int(t1) + time_to_int(t2)
  return int_to_time(seconds)

Or you could use an assert statement, which checks a given invariant
and raises an exception if it fails:

def add_time(t1, t2):
  assert valid_time(t1) and valid_time(t2)
  seconds = time_to_int(t1) + time_to_int(t2)
  return int_to_time(seconds)

assert statements are useful because they distinguish
code that deals with normal conditions from code
that checks for errors.

Glossary[edit]

prototype and patch:
A development plan that involves
writing a rough draft of a program, testing, and correcting errors as
they are found.
planned development:
A development plan that involves
high-level insight into the problem and more planning than incremental
development or prototype development.
pure function:
A function that does not modify any of the objects it
receives as arguments. Most pure functions are fruitful.
modifier:
A function that changes one or more of the objects it
receives as arguments. Most modifiers are fruitless.
functional programming style:
A style of program design in which the
majority of functions are pure.
invariant:
A condition that should always be true during the
execution of a program.

Exercises[edit]

Exercise 6[edit]

Write a function called mul_time that takes a Time object
and a number and returns a new Time object that contains
the product of the original Time and the number.
Then use mul_time to write a function that takes a Time
object that represents the finishing time in a race, and a number
that represents the distance, and returns a Time object that represents
the average pace (time per mile).

Exercise 7[edit]

Write a class definition for a Date object that has attributes 'day', 'month' and 'year'. Write a function called
increment_date that takes a Date object, 'date' and an
integer, 'n', and returns a new Date object that
represents the day 'n' days after 'date'. Hint:
“Thirty days hath September...” Challenge: does your function
deal with leap years correctly? See ''wikipedia.org/wiki/Leap_year

Exercise 8[edit]

The 'datetime' module provides 'date' and 'time' objects
that are similar to the Date and Time objects in this chapter, but
they provide a rich set of methods and operators. Read the
documentation at 'docs.python.org/lib/datetime-date.html'.

  • Use the 'datetime' module to write a program that gets the current date and prints the day of the week.
  • Write a program that takes a birthday as input and prints the user’s age and the number of days, hours, minutes and seconds until their next birthday.

Object-oriented features[edit]

Python is an object-oriented programming language, which means
that it provides features that support object-oriented
programming.

It is not easy to define object-oriented programming, but we have
already seen some of its characteristics:

  • Programs are made up of object definitions and function definitions, and most of the computation is expressed in terms of operations on objects.
  • Each object definition corresponds to some object or concept in the real world, and the functions that operate on that object correspond to the ways real-world objects interact.

For example, the Time class defined in Chapter 16
corresponds to the way people record the time of day, and the
functions we defined correspond to the kinds of things people do with
times. Similarly, the Point and Rectangle classes
correspond to the mathematical concepts of a point and a rectangle.

So far, we have not taken advantage of the features Python provides to
support object-oriented programming. These
features are not strictly necessary; most of them provide
alternative syntax for things we have already done. But in many cases,
the alternative is more concise and more accurately conveys the
structure of the program.

For example, in the Time program, there is no obvious
connection between the class definition and the function definitions
that follow. With some examination, it is apparent that every function
takes at least one Time object as an argument.

This observation is the motivation for methods; a method is
a function that is associated with a particular class.
We have seen methods for strings, lists, dictionaries and tuples.
In this chapter, we will define methods for user-defined types.

Methods are semantically the same as functions, but there are
two syntactic differences:

  • Methods are defined inside a class definition in order to make the relationship between the class and the method explicit.
  • The syntax for invoking a method is different from the syntax for calling a function.

In the next few sections, we will take the functions from the previous
two chapters and transform them into methods. This transformation is
purely mechanical; you can do it simply by following a sequence of
steps. If you are comfortable converting from one form to another,
you will be able to choose the best form for whatever you are doing.

Printing objects[edit]

In Chapter 16, we defined a class named
Time and in Exercise 16.1, you
wrote a function named print_time:

class Time(object):
    """represents the time of day.
       attributes: hour, minute, second"""

def print_time(time):
    print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)

To call this function, you have to pass a Time object as an
argument:

>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> print_time(start)
09:45:00

To make print_time a method, all we have to do is
move the function definition inside the class definition. Notice
the change in indentation.

class Time(object):
    def print_time(time):
        print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)

Now there are two ways to call print_time. The first
(and less common) way is to use function syntax:

>>> Time.print_time(start)
09:45:00

In this use of dot notation, Time is the name of the class,
and print_time is the name of the method. start is
passed as a parameter.

The second (and more concise) way is to use method syntax:

>>> start.print_time()
09:45:00

In this use of dot notation, print_time is the name of the
method (again), and start is the object the method is
invoked on, which is called the subject. Just as the
subject of a sentence is what the sentence is about, the subject
of a method invocation is what the method is about.

Inside the method, the subject is assigned to the first
parameter, so in this case start is assigned
to time.

By convention, the first parameter of a method is
called self, so it would be more common to write
print_time like this:

class Time(object):
    def print_time(self):
        print '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

The reason for this convention is an implicit metaphor:

  • The syntax for a function call, print_time(start),

suggests that the function is the active agent. It says something
like, “Hey print_time! Here’s an object for you to print.”

  • In object-oriented programming, the objects are the active agents.

A method invocation like start.print_time() says
“Hey start! Please print yourself.”

This change in perspective might be more polite, but it is not obvious
that it is useful. In the examples we have seen so far, it may not
be. But sometimes shifting responsibility from the functions onto the
objects makes it possible to write more versatile functions, and makes
it easier to maintain and reuse code.

Exercise 1[edit]

Rewrite time_to_int
(from Section '16.4') as a method. It is probably not
appropriate to rewrite int_to_time as a method; it’s not
clear what object you would invoke it on!

Another example[edit]

Here’s a version of increment (from Section 16.3)
rewritten as a method:

# inside class Time:

    def increment(self, seconds):
        seconds += self.time_to_int()
        return int_to_time(seconds)

This version assumes that time_to_int is written
as a method, as in Exercise 17.1. Also, note that
it is a pure function, not a modifier.

Here’s how you would invoke increment:

>>> start.print_time()
09:45:00
>>> end = start.increment(1337)
>>> end.print_time()
10:07:17

The subject, start, gets assigned to the first parameter,
self. The argument, 1337, gets assigned to the
second parameter, seconds.

This mechanism can be confusing, especially if you make an error.
For example, if you invoke increment with two arguments, you
get:

>>> end = start.increment(1337, 460)
TypeError: increment() takes exactly 2 arguments (3 given)

The error message is initially confusing, because there are
only two arguments in parentheses. But the subject is also
considered an argument, so all together that’s three.

A more complicated example[edit]

is_after (from Exercise 16.2) is slightly more complicated
because it takes two Time objects as parameters. In this case it is
conventional to name the first parameter self and the second
parameter other:

# inside class Time:

    def is_after(self, other):
        return self.time_to_int() > other.time_to_int()

To use this method, you have to invoke it on one object and pass
the other as an argument:

>>> end.is_after(start)
True

One nice thing about this syntax is that it almost reads
like English: “end is after start?”

The init method[edit]

The init method (short for “initialization”) is
a special method that gets invoked when an object is instantiated.
Its full name is __init__ (two underscore characters,
followed by init, and then two more underscores). An
init method for the Time class might look like this:

# inside class Time:

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second

It is common for the parameters of __init__
to have the same names as the attributes. The statement

        self.hour = hour

stores the value of the parameter hour as an attribute
of self.

The parameters are optional, so if you call Time with
no arguments, you get the default values.

>>> time = Time()
>>> time.print_time()
00:00:00

If you provide one argument, it overrides hour:

>>> time = Time (9)
>>> time.print_time()
09:00:00

If you provide two arguments, they override hour and
minute.

>>> time = Time(9, 45)
>>> time.print_time()
09:45:00

And if you provide three arguments, they override all three
default values.

Exercise 2[edit]

Write an init method for the 'Point' class that takes
'x' and 'y' as optional parameters and assigns
them to the corresponding attributes.

The __str__ method[edit]

__str__ is a special method, like __init__,
that is supposed to return a string representation of an object.

For example, here is a str method for Time objects:

# inside class Time:

    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

When you print an object, Python invokes the str method:

>>> time = Time(9, 45)
>>> print time
09:45:00

When I write a new class, I almost always start by writing
__init__, which makes it easier to instantiate objects, and
__str__, which is useful for debugging.

Exercise 3[edit]

Write a 'str' method for the 'Point' class. Create
a Point object and print it.

Operator overloading[edit]

By defining other special methods, you can specify the behavior
of operators on user-defined types. For example, if you define
a method named __add__ for the Time class, you can use the
+ operator on Time objects.

Here is what the definition might look like:

# inside class Time:

    def __add__(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

And here is how you could use it:

>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00

When you apply the + operator to Time objects, Python invokes
__add__. When you print the result, Python invokes
__str__. So there is quite a lot happening behind the scenes!

Changing the behavior of an operator so that it works with
user-defined types is called operator overloading. For every
operator in Python there is a corresponding special method, like
__add__. For more details, see
docs.python.org/ref/specialnames.html.

Exercise 4[edit]

Write an 'add' method for the Point class.

Type-based dispatch[edit]

In the previous section we added two Time objects, but you
also might want to add an integer to a Time object. The
following is a version of __add__
that checks the type of other and invokes either
add_time or increment:

# inside class Time:

    def __add__(self, other):
        if isinstance(other, Time):
            return self.add_time(other)
        else:
            return self.increment(other)

    def add_time(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

    def increment(self, seconds):
        seconds += self.time_to_int()
        return int_to_time(seconds)

The built-in function isinstance takes a value and a
class object, and returns True if the value is an instance
of the class.

If other is a Time object, __add__ invokes
add_time. Otherwise it assumes that the parameter
is a number and invokes increment. This operation is
called a type-based dispatch because it dispatches the
computation to different methods based on the type of the
arguments.

Here are examples that use the + operator with different
types:

>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00
>>> print start + 1337
10:07:17

Unfortunately, this implementation of addition is not commutative.
If the integer is the first operand, you get

>>> print 1337 + start
TypeError: unsupported operand type(s) for +: 'int' and 'instance'

The problem is, instead of asking the Time object to add an integer,
Python is asking an integer to add a Time object, and it doesn’t know
how to do that. But there is a clever solution for this problem: the
special method __radd__, which stands for “right-side add.”
This method is invoked when a Time object appears on the right side of
the + operator. Here’s the definition:

# inside class Time:

    def __radd__(self, other):
        return self.__add__(other)

And here’s how it’s used:

>>> print 1337 + start
10:07:17

Exercise 5[edit]

Write an 'add' method for Points that works with either a
Point object or a tuple:

  • If the second operand is a Point, the method should return a new Point whose 'x' coordinate is the sum of the 'x' coordinates of the operands, and likewise for the 'y' coordinates.
  • If the second operand is a tuple, the method should add the first element of the tuple to the 'x' coordinate and the second element to the 'y' coordinate, and return a new Point with the result.

Polymorphism[edit]

Type-based dispatch is useful when it is necessary, but (fortunately)
it is not always necessary. Often you can avoid it by writing functions
that work correctly for arguments with different types.

Many of the functions we wrote for strings will actually
work for any kind of sequence.
For example, in Section 11.1
we used histogram to count the number of times each letter
appears in a word.

def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] = d[c]+1
    return d

This function also works for lists, tuples, and even dictionaries,
as long as the elements of s are hashable, so they can be used
as keys in d.

>>> t = ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']
>>> histogram(t)
{'bacon': 1, 'egg': 1, 'spam': 4}

Functions that can work with several types are called polymorphic.
Polymorphism can facilitate code reuse. For example, the built-in
function sum, which adds the elements of a sequence, works
as long as the elements of the sequence support addition.

Since Time objects provide an add method, they work
with sum:

>>> t1 = Time(7, 43)
>>> t2 = Time(7, 41)
>>> t3 = Time(7, 37)
>>> total = sum([t1, t2, t3])
>>> print total
23:01:00

In general, if all of the operations inside a function
work with a given type, then the function works with that type.

The best kind of polymorphism is the unintentional kind, where
you discover that a function you already wrote can be
applied to a type you never planned for.

Debugging[edit]

It is legal to add attributes to objects at any point in the execution
of a program, but if you are a stickler for type theory, it is a
dubious practice to have objects of the same type with different
attribute sets. It is usually a good idea to
initialize all of an objects attributes in the init method.

If you are not sure whether an object has a particular attribute, you
can use the built-in function hasattr (see Section 15.7).

Another way to access the attributes of an object is through the
special attribute __dict__, which is a dictionary that maps
attribute names (as strings) and values:

>>> p = Point(3, 4)
>>> print p.__dict__
{'y': 4, 'x': 3}

For purposes of debugging, you might find it useful to keep this
function handy:

def print_attributes(obj):
    for attr in obj.__dict__:
        print attr, getattr(obj, attr)

print_attributes traverses the items in the object’s dictionary
and prints each attribute name and its corresponding value.

The built-in function getattr takes an object and an attribute
name (as a string) and returns the attribute’s value.

Glossary[edit]

object-oriented language:
A language that provides features,
such as user-defined classes and method syntax, that facilitate
object-oriented programming.
object-oriented programming:
A style of programming in which
data and the operations that manipulate it are organized into classes
and methods.
method:
A function that is defined inside a class definition and
is invoked on instances of that class.
subject:
The object a method is invoked on.
operator overloading:
Changing the behavior of an operator like
+ so it works with a user-defined type.

type-based dispatch:
A programming pattern that checks the type
of an operand and invokes different functions for different types.
polymorphic:
Pertaining to a function that can work with more
than one type.

Exercises[edit]

Exercise 6[edit]

This exercise is a cautionary tale about one of the most
common, and difficult to find, errors in Python.

  • Write a definition for a class named 'Kangaroo' with the following

methods:

  • An __init__ method that initializes an attribute named pouch_contents to an empty list.
  • A method named put_in_pouch that takes an object of any type and adds it to pouch_contents.
  • A __str__ method that returns a string representation of the Kangaroo object and the contents of the pouch.

Test your code
by creating two '''Kangaroo''' objects, assigning them to variables
named '''kanga''' and '''roo''', and then adding '''roo''' to the
contents of '''kanga'''’s pouch.'

  • 'Download '''thinkpython.com/code/BadKangaroo.py'''. It contains

a solution to the previous problem with one big, nasty bug.
Find and fix the bug.'
'If you get stuck, you can download
'''thinkpython.com/code/GoodKangaroo.py''', which explains the
problem and demonstrates a solution.'

Exercise 7[edit]

Visual is a Python module that provides 3-D graphics. It is
not always included in a Python installation, so you might have
to install it from your software repository or, if it’s not there,
from 'vpython.org'.

The following example creates a 3-D space that is 256 units
wide, long and high, and sets the “center” to be the
point '(128, 128, 128)'. Then it draws a blue sphere.

''from visual import *

scene.range = (256, 256, 256)
scene.center = (128, 128, 128)

color = (0.1, 0.1, 0.9)          # mostly blue
sphere(pos=scene.center, radius=128, color=color)
''

color'' is an RGB tuple; that is, the elements are Red-Green-Blue
levels between 0.0 and 1.0 (see
'wikipedia.org/wiki/RGB_color_model').

If you run this code, you should see a window with a black
background and a blue sphere. If you drag the middle button
up and down, you can zoom in and out. You can also rotate
the scene by dragging the right button, but with only one
sphere in the world, it is hard to tell the difference.

The following loop creates a cube of spheres:

''t = range(0, 256, 51)
for x in t:
    for y in t:
        for z in t:
            pos = x, y, z
            sphere(pos=pos, radius=10, color=color)
''
  • Put this code in a script and make sure it works for

you.

  • Modify the program so that each sphere in the cube

has the color that corresponds to its position in RGB space.
Notice that the coordinates are in the range 0–255, but
the RGB tuples are in the range 0.0–1.0.

  • Download 'thinkpython.com/code/color_list.py'

and use the function read_colors to generate a list
of the available colors on your system, their names and
RGB values. For each named color draw a sphere in the
position that corresponds to its RGB values.

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

Further reading[edit]

In this chapter we will develop classes to represent playing cards,
decks of cards, and poker hands. If you don’t play poker, you can
read about it at wikipedia.org/wiki/Poker, but you don't have
to; I'll tell you what you need to know for the exercises.

If you are not familiar with Anglo-American playing cards,
you can read about them at wikipedia.org/wiki/Playing_cards.

Card objects[edit]

There are fifty-two cards in a deck, each of which belongs to one of
four suits and one of thirteen ranks. The suits are Spades, Hearts,
Diamonds, and Clubs (in descending order in bridge). The ranks are
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. Depending on
the game that you are playing, an Ace may be higher than King
or lower than 2.

If we want to define a new object to represent a playing card, it is
obvious what the attributes should be: rank and
suit. It is not as obvious what type the attributes
should be. One possibility is to use strings containing words like
'Spade' for suits and 'Queen' for ranks. One problem with
this implementation is that it would not be easy to compare cards to
see which had a higher rank or suit.

An alternative is to use integers to encode the ranks and suits.
In this context, “encode” means that we are going to define a mapping
between numbers and suits, or between numbers and ranks. This
kind of encoding is not meant to be a secret (that
would be “encryption”).

For example, this table shows the suits and the corresponding integer
codes:

Spades 3
Hearts 2
Diamonds 1
Clubs 0

This code makes it easy to compare cards; because higher suits map to
higher numbers, we can compare suits by comparing their codes.

The mapping for ranks is fairly obvious; each of the numerical ranks
maps to the corresponding integer, and for face cards:

Jack 11
Queen 12
King 13

I am using the ↦ symbol to make it clear that these mappings
are not part of the Python program. They are part of the program
design, but they don’t appear explicitly in the code.

The class definition for Card looks like this:

class Card:
    """represents a standard playing card."""

    def __init__(self, suit=0, rank=2):
        self.suit = suit
        self.rank = rank

As usual, the init method takes an optional
parameter for each attribute. The default card is
the 2 of Clubs.

To create a Card, you call Card with the
suit and rank of the card you want.

queen_of_diamonds = Card(1, 12)

Class attributes[edit]

In order to print Card objects in a way that people can easily
read, we need a mapping from the integer codes to the corresponding
ranks and suits. A natural way to
do that is with lists of strings. We assign these lists to class
attributes:

# inside class Card:

    suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', 
              '8', '9', '10', 'Jack', 'Queen', 'King']

    def __str__(self):
        return '%s of %s' % (Card.rank_names[self.rank],
                             Card.suit_names[self.suit])

Variables like suit_names and rank_names, which are
defined inside a class but outside of any method, are called
class attributes because they are associated with the class object
Card.

This term distinguished them from variables like suit and rank, which are called instance attributes because they are
associated with a particular instance.

Both kinds of attribute are accessed using dot notation. For
example, in __str__, self is a Card object,
and self.rank is its rank. Similarly, Card
is a class object, and Card.rank_names is a
list of strings associated with the class.

Every card has its own suit and rank, but there
is only one copy of suit_names and rank_names.

Putting it all together, the expression
Card.rank_names[self.rank] means “use the attribute rank
from the object self as an index into the list rank_names
from the class Card, and select the appropriate string.”

The first element of rank_names is None because there
is no card with rank zero. By including None as a place-keeper,
we get a mapping with the nice property that the index 2 maps to the
string '2', and so on. To avoid this tweak, we could have
used a dictionary instead of a list.

With the methods we have so far, we can create and print cards:

>>> card1 = Card(2, 11)
>>> print card1
Jack of Hearts

Here is a diagram that shows the Card class object
and one Card instance:

Card is a class object, so it has type type. card1 has type Card. (To save space, I didn’t draw the
contents of suit_names and rank_names).

Comparing cards[edit]

For built-in types, there are conditional operators
(<, >, ==, etc.)
that compare
values and determine when one is greater than, less than, or equal to
another. For user-defined types, we can override the behavior of
the built-in operators by providing a method named
__cmp__.

__cmp__ takes two parameters, self and other,
and returns a positive number if the first object is greater, a
negative number if the second object is greater, and 0 if they are
equal to each other.

The correct ordering for cards is not obvious.
For example, which
is better, the 3 of Clubs or the 2 of Diamonds? One has a higher
rank, but the other has a higher suit. In order to compare
cards, you have to decide whether rank or suit is more important.

The answer might depend on what game you are playing, but to keep
things simple, we’ll make the arbitrary choice that suit is more
important, so all of the Spades outrank all of the Diamonds,
and so on.

With that decided, we can write __cmp__:

# inside class Card:

    def __cmp__(self, other):
        # check the suits
        if self.suit > other.suit: return 1
        if self.suit < other.suit: return -1

        # suits are the same... check ranks
        if self.rank > other.rank: return 1
        if self.rank < other.rank: return -1

        # ranks are the same... it's a tie
        return 0    

You can write this more concisely using tuple comparison:

# inside class Card:

    def __cmp__(self, other):
        t1 = self.suit, self.rank
        t2 = other.suit, other.rank
        return cmp(t1, t2)

The built-in function cmp has the same interface as
the method __cmp__: it takes two values and returns
a positive number if the first is larger, a negative number
of the second is larger, and 0 if they are equal.

Exercise 1[edit]

Write a __cmp__ method for Time objects. Hint: you
can use tuple comparison, but you also might consider using
integer subtraction.

Now that we have Cards, the next step is to define Decks. Since a
deck is made up of cards, it is natural for each Deck to contain a
list of cards as an attribute.

The following is a class definition for Deck. The
init method creates the attribute cards and generates
the standard set of fifty-two cards:

class Deck:

    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(suit, rank)
                self.cards.append(card)

The easiest way to populate the deck is with a nested loop. The outer
loop enumerates the suits from 0 to 3. The inner loop enumerates the
ranks from 1 to 13. Each iteration
creates a new Card with the current suit and rank,
and appends it to self.cards.

Printing the deck[edit]

Here is a __str__ method for Deck:

#inside class Deck:

    def __str__(self):
        res = [str(card) for card in self.cards]
        return 'n'.join(res)

This method demonstrates an efficient way to accumulate a large
string: building a list of strings and then using join.
The built-in function str invokes the __str__
method on each card and returns the string representation.

Since we invoke join on a newline character, the cards
are separated by newlines. Here’s what the result looks like:

>>> deck = Deck()
>>> print deck
Ace of Clubs
2 of Clubs
3 of Clubs
...
10 of Spades
Jack of Spades
Queen of Spades
King of Spades

Even though the result appears on 52 lines, it is
one long string that contains newlines.

Add, remove, shuffle and sort[edit]

To deal cards, we would like a method that
removes a card from the deck and returns it.
The list method pop provides a convenient way to do that:

#inside class Deck:

    def pop_card(self):
        return self.cards.pop()

Since pop removes the last card in the list, we are
dealing from the bottom of the deck. In real life bottom dealing is
frowned upon1,
but in this context it’s ok.

To add a card, we can use the list method append:

#inside class Deck:

    def add_card(self, card):
        self.cards.append(card)

A method like this that uses another function without doing
much real work is sometimes called a veneer. The metaphor
comes from woodworking, where it is common to glue a thin
layer of good quality wood to the surface of a cheaper piece of
wood.

In this case we are defining a “thin” method that expresses
a list operation in terms that are appropriate for decks.

As another example, we can write a Deck method named shuffle
using the function shuffle from the random module:

# inside class Deck:
            
    def shuffle(self):
        random.shuffle(self.cards)

Don’t forget to import random.

Exercise 2[edit]

Write a Deck method named 'sort' that uses the list method
'sort' to sort the cards in a 'Deck'. 'sort' uses
the __cmp__ method we defined to determine sort order.

Inheritance[edit]

The language feature most often associated with object-oriented
programming is inheritance. Inheritance is the ability to
define a new class that is a modified version of an existing
class.

It is called “inheritance” because the new class inherits the
methods of the existing class. Extending this metaphor, the existing
class is called the parent and the new class is
called the child.

As an example, let’s say we want a class to represent a “hand,”
that is, the set of cards held by one player. A hand is similar to a
deck: both are made up of a set of cards, and both require operations
like adding and removing cards.

A hand is also different from a deck; there are operations we want for
hands that don’t make sense for a deck. For example, in poker we
might compare two hands to see which one wins. In bridge, we might
compute a score for a hand in order to make a bid.

This relationship between classes—similar, but different—lends
itself to inheritance.

The definition of a child class is like other class definitions,
but the name of the parent class appears in parentheses:

class Hand(Deck):
    """represents a hand of playing cards"""

This definition indicates that Hand inherits from Deck;
that means we can use methods like pop_card and add_card
for Hands as well as Decks.

Hand also inherits __init__ from Deck, but
it doesn’t really do what we want: instead of populating the hand
with 52 new cards, the init method for Hands should initialize
cards with an empty list.

If we provide an init method in the Hand class, it overrides the
one in the Deck class:

# inside class Hand:

    def __init__(self, label=""):
        self.cards = []
        self.label = label

So when you create a Hand, Python invokes this init method:

>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand

But the other methods are inherited from Deck, so we can use
pop_card and add_card to deal a card:

>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card)
>>> print hand
King of Spades

A natural next step is to encapsulate this code in a method
called move_cards:

#inside class Deck:

    def move_cards(self, hand, num):
        for i in range(num):
            hand.add_card(self.pop_card())

move_cards takes two arguments, a Hand object and the number of
cards to deal. It modifies both self and hand, and
returns None.

In some games, cards are moved from one hand to another,
or from a hand back to the deck. You can use move_cards
for any of these operations: self can be either a Deck
or a Hand, and hand, despite the name, can also be a Deck.

Exercise 3  

Write a Deck method called deal_hands that takes two
parameters, the number of hands and the number of cards per
hand, and that creates new Hand objects, deals the appropriate
number of cards per hand, and returns a list of Hand objects.

Inheritance is a useful feature. Some programs that would be
repetitive without inheritance can be written more elegantly
with it. Inheritance can facilitate code reuse, since you can
customize the behavior of parent classes without having to modify
them. In some cases, the inheritance structure reflects the natural
structure of the problem, which makes the program easier to
understand.

On the other hand, inheritance can make programs difficult to read.
When a method is invoked, it is sometimes not clear where to find its
definition. The relevant code may be scattered among several modules.
Also, many of the things that can be done using inheritance can be
done as well or better without it.

Class diagrams[edit]

So far we have seen stack diagrams, which show the state of
a program, and object diagrams, which show the attributes
of an object and their values. These diagrams represent a snapshot
in the execution of a program, so they change as the program
runs.

They are also highly detailed; for some purposes, too
detailed. A class diagrams is a more abstract representation
of the structure of a program. Instead of showing individual
objects, it shows classes and the relationships between them.

There are several kinds of relationship between classes:

  • Objects in one class might contain references to objects in another class. For example, each Rectangle contains a reference to a Point, and each Deck contains references to many Cards. This kind of relationship is called HAS-A, as in, “a Rectangle has a Point.”
  • One class might inherit from another. This relationship is called IS-A, as in, “a Hand is a kind of a Deck.”
  • One class might depend on another in the sense that changes in one class would require changes in the other.

A class diagram is a graphical representation of these
relationships2. For example, this diagram shows the
relationships between Card, Deck and Hand.

The arrow with a hollow triangle head represents an IS-A
relationship; in this case it indicates that Hand inherits
from Deck.

The standard arrow head represents a HAS-A
relationship; in this case a Deck has references to Card
objects.

The star (*) near the arrow head is a
multiplicity; it indicates how many Cards a Deck has.
A multiplicity can be a simple number, like 52, a range,
like 5..7 or a star, which indicates that a Deck can
have any number of Cards.

A more detailed diagram might show that a Deck actually
contains a list of Cards, but built-in types
like list and dict are usually not included in class diagrams.

Exercise 4[edit]

Read 'TurtleWorld.py', 'World.py' and 'Gui.py'
and draw a class diagram that shows the relationships among
the classes defined there.

Debugging[edit]

Inheritance can make debugging a challenge because when you
invoke a method on an object, you might not know which method
will be invoked.

Suppose you are writing a function that works with Hand objects.
You would like it to work with all kinds of Hands, like
PokerHands, BridgeHands, etc. If you invoke a method like
shuffle, you might get the one defined in Deck,
but if any of the subclasses override this method, you’ll
get that version instead.

Any time you are unsure about the flow of execution through your
program, the simplest solution is to add print statements at the
beginning of the relevant methods. If Deck.shuffle prints a
message that says something like Running Deck.shuffle, then as
the program runs it traces the flow of execution.

As an alternative, you could use this function, which takes an
object and a method name (as a string) and returns the class that
provides the definition of the method:

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

Here’s an example:

>>> hand = Hand()
>>> print find_defining_class(hand, 'shuffle')

So the shuffle method for this Hand is the one in Deck.

find_defining_class uses the mro method to get the list
of class objects (types) that will be searched for methods. “MRO”
stands for “method resolution order.”

Here’s a program design suggestion: whenever you override a method,
the interface of the new method should be the same as the old. It
should take the same parameters, return the same type, and obey the
same preconditions and postconditions. If you obey this rule, you
will find that any function designed to work with an instance of a
superclass, like a Deck, will also work with instances of subclasses
like a Hand or PokerHand.

If you violate this rule, your code will collapse like (sorry)
a house of cards.

Glossary[edit]

encode:
To represent one set of values using another
set of values by constructing a mapping between them.
class attribute:
An attribute associated with a class
object. Class attributes are defined inside
a class definition but outside any method.

instance attribute:
An attribute associated with an
instance of a class.

veneer:
A method or function that provides a different
interface to another function without doing much computation.
inheritance:
The ability to define a new class that is a
modified version of a previously defined class.
parent class:
The class from which a child class inherits.
child class:
A new class created by inheriting from an
existing class; also called a “subclass.”
IS-A relationship:
The relationship between a child class
and its parent class.
HAS-A relationship:
The relationship between two classes
where instances of one class contain references to instances of
the other.
class diagram:
A diagram that shows the classes in a program
and the relationships between them.

multiplicity:
A notation in a class diagram that shows, for
a HAS-A relationship, how many references there are to instances
of another class.

Exercises[edit]

Exercise 5[edit]

The following are the possible hands in poker, in increasing order
of value (and decreasing order of probability):

pair:
two cards with the same rank
''two pair:''
two pairs of cards with the same rank
''three of a kind:''
three cards with the same rank
''straight:''
five cards with ranks in sequence (aces can
be high or low, so 'Ace-2-3-4-5' is a straight and so is '10-Jack-Queen-King-Ace', but 'Queen-King-Ace-2-3' is not.)
''flush:''
five cards with the same suit
''full house:''
three cards with one rank, two cards with another
''four of a kind:''
four cards with the same rank
''straight flush:''
five cards in sequence (as defined above) and
with the same suit


The goal of these exercises is to estimate
the probability of drawing these various hands.

  • Download the following files from 'thinkpython.com/code':
    Card.py
    : A complete version of the 'Card', 'Deck' and 'Hand' classes in this chapter.
    ''PokerHand.py''
    : An incomplete implementation of a class

that represents a poker hand, and some code that tests it.

  • 'If you run '''PokerHand.py''', it deals six 7-card poker hands

and checks to see if any of them contains a flush. Read this
code carefully before you go on.'

  • 'Add methods to '''PokerHand.py''' named ''has_pair'',

''has_twopair'', etc. that return True or False according to
whether or not the hand meets the relevant criteria. Your code should
work correctly for “hands” that contain any number of cards
(although 5 and 7 are the most common sizes).'

  • 'Write a method named '''classify''' that figures out

the highest-value classification for a hand and sets the
'''label''' attribute accordingly. For example, a 7-card hand
might contain a flush and a pair; it should be labeled “flush”.'

  • 'When you are convinced that your classification methods are

working, the next step is to estimate the probabilities of the various
hands. Write a function in '''PokerHand.py''' that shuffles a deck of
cards, divides it into hands, classifies the hands, and counts the
number of times various classifications appear.'

  • 'Print a table of the classifications and their probabilities.

Run your program with larger and larger numbers of hands until the
output values converge to a reasonable degree of accuracy. Compare
your results to the values at '''wikipedia.org/wiki/Hand_rankings'''.'

Exercise 6[edit]

This exercise uses TurtleWorld from Chapter '4'.
You will write code that makes Turtles play tag. If you
are not familiar with the rules of tag, see
'wikipedia.org/wiki/Tag_(game)'.

  • Download 'thinkpython.com/code/Wobbler.py' and run it. You

should see a TurtleWorld with three Turtles. If you press the
'Run' button, the Turtles wander at random.

  • Read the code and make sure you understand how it works.

The 'Wobbler' class inherits from 'Turtle', which means
that the 'Turtle' methods 'lt', 'rt', 'fd'
and 'bk' work on Wobblers.
The 'step' method gets invoked by TurtleWorld. It invokes
'steer', which turns the Turtle in the desired direction,
'wobble', which makes a random turn in proportion to the Turtle’s
clumsiness, and 'move', which moves forward a few pixels,
depending on the Turtle’s speed.

  • Create a file named 'Tagger.py'. Import everything from

'Wobbler', then define a class named 'Tagger' that inherits
from 'Wobbler'. Call make_world passing the 'Tagger' class object as an argument.

  • Add a 'steer' method to 'Tagger' to override the one in

'Wobbler'. As a starting place, write a version that always
points the Turtle toward the origin. Hint: use the math function
'atan2' and the Turtle attributes 'x', 'y' and
'heading'.

  • Modify 'steer' so that the Turtles stay in bounds.

For debugging, you might want to use the 'Step' button,
which invokes 'step' once on each Turtle.

  • Modify 'steer' so that each Turtle points toward its nearest

neighbor. Hint: Turtles have an attribute, 'world', that is a
reference to the TurtleWorld they live in, and the TurtleWorld has
an attribute, 'animals', that is a list of all Turtles in the
world.

  • Modify 'steer' so the Turtles play tag. You can add methods

to 'Tagger' and you can override 'steer' and
__init__, but you may not modify or override 'step', 'wobble' or 'move'. Also, 'steer' is allowed to change the
heading of the Turtle but not the position.
Adjust the rules and your 'steer' method for good quality play;
for example, it should be possible for the slow Turtle to tag the
faster Turtles eventually.

You can get my solution from 'thinkpython.com/code/Tagger.py'.

Different kinds of errors can occur
in a program, and it is useful to distinguish among them
in order to track them down more quickly:

  • Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.
  • Runtime errors are produced by the interpreter if something goes wrong while the program is running. Most runtime error messages include information about where the error occurred and what functions were executing. Example: An infinite recursion eventually causes the runtime error “maximum recursion depth exceeded.”
  • Semantic errors are problems with a program that runs without producing error messages but doesn’t do the right thing. Example: An expression may not be evaluated in the order you expect, yielding an incorrect result.

The first step in debugging is to figure out which kind of
error you are dealing with. Although the following sections are
organized by error type, some techniques are
applicable in more than one situation.

Syntax errors[edit]

Syntax errors are usually easy to fix once you figure out what they
are. Unfortunately, the error messages are often not helpful.
The most common messages are SyntaxError: invalid syntax and
SyntaxError: invalid token, neither of which is very informative.

On the other hand, the message does tell you where in the program the
problem occurred. Actually, it tells you where Python
noticed a problem, which is not necessarily where the error
is. Sometimes the error is prior to the location of the error
message, often on the preceding line.

If you are building the program incrementally, you should have
a good idea about where the error is. It will be in the last
line you added.

If you are copying code from a book, start by comparing
your code to the book’s code very carefully. Check every character.
At the same time, remember that the book might be wrong, so
if you see something that looks like a syntax error, it might be.

Here are some ways to avoid the most common syntax errors:

  • Make sure you are not using a Python keyword for a variable name.
  • Check that you have a colon at the end of the header of every

compound statement, including for, while,
if, and def statements.

  • Make sure that any strings in the code have matching

quotation marks.

  • If you have multiline strings with triple quotes (single or double), make

sure you have terminated the string properly. An unterminated string
may cause an invalid token error at the end of your program,
or it may treat the following part of the program as a string until it
comes to the next string. In the second case, it might not produce an error
message at all!

  • An unclosed opening operator—(, {, or

[—makes Python continue with the next line as part of the
current statement. Generally, an error occurs almost immediately in
the next line.

  • Check for the classic = instead of == inside

a conditional.

  • Check the indentation to make sure it lines up the way it

is supposed to. Python can handle space and tabs, but if you mix
them it can cause problems. The best way to avoid this problem
is to use a text editor that knows about Python and generates
consistent indentation.

If nothing works, move on to the next section...

I keep making changes and it makes no difference.[edit]

If the interpreter says there is an error and you don’t see it, that
might be because you and the interpreter are not looking at the same
code. Check your programming environment to make sure that the
program you are editing is the one Python is trying to run.

If you are not sure, try putting an obvious and deliberate syntax
error at the beginning of the program. Now run it again. If the
interpreter doesn’t find the new error, you are not running the
new code.

There are a few likely culprits:

  • You edited the file and forgot to save the changes before running it again. Some programming environments do this for you, but some don’t.
  • You changed the name of the file, but you are still running the old name.
  • Something in your development environment is configured incorrectly.
  • If you are writing a module and using import, make sure you don’t give your module the same name as one of the standard Python modules.
  • If you are using import to read a module, remember that you have to restart the interpreter or use reload to read a modified file. If you import the module again, it doesn’t do anything.

If you get stuck and you can’t figure out what is going on, one
approach is to start again with a new program like “Hello, World!,”
and make sure you can get a known program to run. Then gradually add
the pieces of the original program to the new one.

Runtime errors[edit]

Once your program is syntactically correct,
Python can compile it and at least start running it. What could
possibly go wrong?

My program does absolutely nothing.[edit]

This problem is most common when your file consists of functions and
classes but does not actually invoke anything to start execution.
This may be intentional if you only plan to import this module to
supply classes and functions.

If it is not intentional, make sure that you
are invoking a function to start execution, or execute one from
the interactive prompt. Also see the “Flow of Execution” section
below.

My program hangs[edit]

If a program stops and seems to be doing nothing, it is “hanging.”
Often that means that it is caught in an infinite loop or infinite
recursion.

  • If there is a particular loop that you suspect is the problem, add a print statement immediately before the loop that says “entering the loop” and another immediately after that says “exiting the loop.” Run the program. If you get the first message and not the second, you’ve got an infinite loop. Go to the “Infinite Loop” section below.
  • Most of the time, an infinite recursion will cause the program to run for a while and then produce a “RuntimeError: Maximum recursion depth exceeded” error. If that happens, go to the “Infinite Recursion” section below. If you are not getting this error but you suspect there is a problem with a recursive method or function, you can still use the techniques in the “Infinite Recursion” section.
  • If neither of those steps works, start testing other loops and other recursive functions and methods.
  • If that doesn’t work, then it is possible that you don’t understand the flow of execution in your program. Go to the “Flow of Execution” section below.

Infinite Loop[edit]

If you think you have an infinite loop and you think you know
what loop is causing the problem, add a print statement at
the end of the loop that prints the values of the variables in
the condition and the value of the condition.

For example:

while x > 0 and y < 0 :
    # do something to x
    # do something to y

    print  "x: ", x
    print  "y: ", y
    print  "condition: ", (x > 0 and y < 0)

Now when you run the program, you will see three lines of output
for each time through the loop. The last time through the
loop, the condition should be false. If the loop keeps
going, you will be able to see the values of x and y,
and you might figure out why they are not being updated correctly.

Infinite Recursion[edit]

Most of the time, an infinite recursion will cause the program to run
for a while and then produce a Maximum recursion depth exceeded
error.

If you suspect that a function or method is causing an infinite
recursion, start by checking to make sure that there is a base case.
In other words, there should be some condition that will cause the
function or method to return without making a recursive invocation.
If not, then you need to rethink the algorithm and identify a base
case.

If there is a base case but the program doesn’t seem to be reaching
it, add a print statement at the beginning of the function or method
that prints the parameters. Now when you run the program, you will see
a few lines of output every time the function or method is invoked,
and you will see the parameters. If the parameters are not moving
toward the base case, you will get some ideas about why not.

Flow of Execution[edit]

If you are not sure how the flow of execution is moving through
your program, add print statements to the beginning of each
function with a message like “entering function foo,” where
foo is the name of the function.

Now when you run the program, it will print a trace of each
function as it is invoked.

When I run the program I get an exception.[edit]

If something goes wrong during runtime, Python
prints a message that includes the name of the
exception, the line of the program where the problem occurred,
and a traceback.

The traceback identifies the function that is currently running,
and then the function that invoked it, and then the function that
invoked that, and so on. In other words, it traces the
sequence of function invocations that got you to where you are. It
also includes the line number in your file where each of these
calls occurs.

The first step is to examine the place in the program where
the error occurred and see if you can figure out what happened.
These are some of the most common runtime errors:

NameError:
You are trying to use a variable that doesn’t
exist in the current environment.
Remember that local variables are local. You
cannot refer to them from outside the function where they are defined.
TypeError:
There are several possible causes:

  • You are trying to use a value improperly. Example: indexing a string, list, or tuple with something other than an integer.
  • There is a mismatch between the items in a format string and the items passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for.
  • You are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is self. Then look at the method invocation; make sure you are invoking the method on an object with the right type and providing the other arguments correctly.
KeyError:
You are trying to access an element of a dictionary
using a key that the dictionary does not contain.

AttributeError:
You are trying to access an attribute or method
that does not exist. Check the spelling! You can use
dir to list the attributes that do exist.
If an AttributeError indicates that an object has NoneType,
that means that it is None. One common cause is forgetting
to return a value from a function; if you get to the end of
a function without hitting a return statement, it returns
None. Another common cause is using the result from
a list method, like sort, that returns None.

IndexError:
The index you are using
to access a list, string, or tuple is greater than
its length minus one. Immediately before the site of the error,
add a print statement to display
the value of the index and the length of the array.
Is the array the right size? Is the index the right value?

The Python debugger (pdb) is useful for tracking down
Exceptions because it allows you to examine the state of the
program immediately before the error. You can read
about pdb at docs.python.org/lib/module-pdb.html.

I added so many print statements I get inundated with output[edit]

One of the problems with using print statements for debugging
is that you can end up buried in output. There are two ways
to proceed: simplify the output or simplify the program.

To simplify the output, you can remove or comment out print
statements that aren’t helping, or combine them, or format
the output so it is easier to understand.

To simplify the program, there are several things you can do. First,
scale down the problem the program is working on. For example, if you
are searching a list, search a small list. If the program takes
input from the user, give it the simplest input that causes the
problem.

Second, clean up the program. Remove dead code and reorganize the
program to make it as easy to read as possible. For example, if you
suspect that the problem is in a deeply nested part of the program,
try rewriting that part with simpler structure. If you suspect a
large function, try splitting it into smaller functions and testing them
separately.

Often the process of finding the minimal test case leads you to the
bug. If you find that a program works in one situation but not in
another, that gives you a clue about what is going on.

Similarly, rewriting a piece of code can help you find subtle
bugs. If you make a change that you think doesn’t affect the
program, and it does, that can tip you off.

Semantic errors[edit]

In some ways, semantic errors are the hardest to debug,
because the interpreter provides no information
about what is wrong. Only you know what the program is supposed to
do.

The first step is to make a connection between the program
text and the behavior you are seeing. You need a hypothesis
about what the program is actually doing. One of the things
that makes that hard is that computers run so fast.

You will often wish that you could slow the program down to human
speed, and with some debuggers you can. But the time it takes to
insert a few well-placed print statements is often short compared to
setting up the debugger, inserting and removing breakpoints, and
“stepping” the program to where the error is occurring.

My program doesn’t work.[edit]

You should ask yourself these questions:

  • Is there something the program was supposed to do but which doesn’t seem to be happening? Find the section of the code that performs that function and make sure it is executing when you think it should.
  • Is something happening that shouldn’t? Find code in your program that performs that function and see if it is executing when it shouldn’t.
  • Is a section of code producing an effect that is not what you expected? Make sure that you understand the code in question, especially if it involves invocations to functions or methods in other Python modules. Read the documentation for the functions you invoke. Try them out by writing simple test cases and checking the results.

In order to program, you need to have a mental model of how
programs work. If you write a program that doesn’t do what you expect,
very often the problem is not in the program; it’s in your mental
model.

The best way to correct your mental model is to break the program
into its components (usually the functions and methods) and test
each component independently. Once you find the discrepancy
between your model and reality, you can solve the problem.

Of course, you should be building and testing components as you
develop the program. If you encounter a problem,
there should be only a small amount of new code
that is not known to be correct.

I’ve got a big hairy expression and it doesn’t do what I expect.[edit]

Writing complex expressions is fine as long as they are readable,
but they can be hard to debug. It is often a good idea to
break a complex expression into a series of assignments to
temporary variables.

For example:

self.hands[i].addCard(self.hands[self.findNeighbor(i)].popCard())

This can be rewritten as:

neighbor = self.findNeighbor(i)
pickedCard = self.hands[neighbor].popCard()
self.hands[i].addCard(pickedCard)

The explicit version is easier to read because the variable
names provide additional documentation, and it is easier to debug
because you can check the types of the intermediate variables
and display their values.

Another problem that can occur with big expressions is
that the order of evaluation may not be what you expect.
For example, if you are translating the expression
x/2 π into Python, you might write:

That is not correct because multiplication and division have
the same precedence and are evaluated from left to right.
So this expression computes x π / 2.

A good way to debug expressions is to add parentheses to make
the order of evaluation explicit:

Whenever you are not sure of the order of evaluation, use
parentheses. Not only will the program be correct (in the sense
of doing what you intended), it will also be more readable for
other people who haven’t memorized the rules of precedence.

I’ve got a function or method that doesn’t return what I expect[edit]

If you have a return statement with a complex expression,
you don’t have a chance to print the return value before
returning. Again, you can use a temporary variable. For
example, instead of:

return self.hands[i].removeMatches()

you could write:

count = self.hands[i].removeMatches()
return count

Now you have the opportunity to display the value of
count before returning.

I'm really, really stuck and I need help.[edit]

First, try getting away from the computer for a few minutes.
Computers emit waves that affect the brain, causing these
symptoms:

  • Superstitious beliefs (“the computer hates me”) and

magical thinking (“the program only works when I wear my
hat backward”).

  • Random walk programming (the attempt to program by writing

every possible program and choosing the one that does the right
thing).

If you find yourself suffering from any of these symptoms, get
up and go for a walk. When you are calm, think about the program.
What is it doing? What are some possible causes of that
behavior? When was the last time you had a working program,
and what did you do next?

Sometimes it just takes time to find a bug. I often find bugs
when I am away from the computer and let my mind wander. Some
of the best places to find bugs are trains, showers, and in bed,
just before you fall asleep.

No, I really need help.[edit]

It happens. Even the best programmers occasionally get stuck.
Sometimes you work on a program so long that you can’t see the
error. A fresh pair of eyes is just the thing.

Before you bring someone else in, make sure you are prepared.
Your program should be as simple
as possible, and you should be working on the smallest input
that causes the error. You should have print statements in the
appropriate places (and the output they produce should be
comprehensible). You should understand the problem well enough
to describe it concisely.

When you bring someone in to help, be sure to give
them the information they need:

  • If there is an error message, what is it and what part of the program does it indicate?
  • What was the last thing you did before this error occurred? What were the last lines of code that you wrote, or what is the new test case that fails?
  • What have you tried so far, and what have you learned?

When you find the bug, take a second to think about what you
could have done to find it faster. Next time you see something
similar, you will be able to find the bug more quickly.

Remember, the goal is not just to make the program
work. The goal is to learn how to make the program work.

Chapter 1[edit]

See below for Chapter 1 exercises.

Exercise 1.2[edit]

3.) If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are about 1.61 kilometers in a mile.)

>>> 10 / 1.61 # convert kilometers to miles

6.211180124223602

>>> (42 * 60) + 42 # convert time to seconds

2562

>>> 2562 / 6.211180124223602 # what is your average time (seconds) per mile

412.482

>>> 412.482 / 60 # what is your average time (minutes) per mile

6.874700000000001

>>> 60 / 6.874700000000001 # miles per hour

8.727653570337614

How about another way

>>> 10 / 42.7 # avg kilometers per minute

0.23419203747072598

>>> 0.23419203747072598 * 60 # kilometers per hour

14.05152224824356

>>> 14.05152224824356 / 1.61 # convert to M.P.H

8.727653570337614

or a one-liner

>>> (10 / 1.61) / (42.7 / 60) # (distance in miles) / (time in hours)

8.727653570337614 # miles/hour

Chapter 2[edit]

Exercise 2.1[edit]

If you type an integer with a leading zero, you might get a confusing error:

>>> zipcode = 02492
                  ^
SyntaxError: invalid token

Other number seem to work, but the results are bizarre:

>>> zipcode = 02132
>>> print zipcode
1114

So python is assuming you want to convert an octal number to a decimal number. In the base 8 numbering system where valid numbers are 0, 1, 2, 3, 4, 5, 6 and 7.

Base  8: 00 01 02 03 04 05 06 07 10 11 12 13 14 15 16 17 20 21 22 23 24
Base 10: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20

Every 8 numbers we increment the left hand columns. This means that the right most column is the number of 'ones'. The one to the left of that is a tally of the number of 'eights', the one next to that is a tally of a full column of 'eight' times the 'eight column' - 64. The one next to that is 64*8 - 512 and so on.
For more information read Base Eight math.

That is why zipcode = 02492 is invalid as the digit 9 is not a valid octal number. We can do the conversion manually as follows:

>>> print 02132
1114
>>> (2*512)+(1*64)+(3*8)+(2*1)
1114
>>> 

Exercise 2.2[edit]

The volume of a sphere with radius r is 4/3 π r3.
What is the volume of a sphere with radius 5?

>>> pi = 3.1415926535897932
>>> r = 5
>>> 4/3*pi*r**3 # This is the wrong answer
392.69908169872411
>>> r = 5.0 # Radius can be a float here as well, but is not _necessary_.
>>> 4.0/3.0*pi*r**3 # Using floats give the correct answer
523.5987755982989
>>> 

Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?

 $24.95  Cost
  $9.98  Discount per book
 $14.97  Cost per book after discount
  60     Total number of books
$898.20  Total cost not inc delivery

  $3.00  First book delivery
  59     Remaining books
  $0.75  Delivery cost for extra books
 $44.25  Total cost for extra books
 $47.25  Total Delivery cost
	
$945.45	 Total Bill

This answer is wrong because 40.0/100.0 return wrong value 0.40000000000000002 for more info see IEEE 754 (Standard for Floating-Point Arithmetic)
>>> (24.95-24.95*40.0/100.0)*60+3+0.75*(60-1)
945.44999999999993
>>> 24.95*0.6*60+0.75*(60-1)+3
945.45

You can use the decimal module to maintain precision.
from decimal import Decimal
..
...
def wholesale_cost(args):

    d = 1 - args.get('discount')/100 
    purchase = Decimal(args.get('cost') * d * 60)
    return purchase + Decimal(args.get('delivery'))

args =  {'cost': 24.95, 'discount': 40, 'delivery': 3.00+0.75*59}

Another solution using functions as well as input prompts:

# Total wholesale book cost calculator
cover_price = 24.95

number_of_books = int(input("How many books do you want to order at wholesale? "))

def ship_cost (number_of_books):
    if number_of_books == 1:
        return (number_of_books * 3) # Cost of shipping one book is $3
    else:
        return (3 + (number_of_books - 1) * 0.75) # Each additional copy of the book is $0.75 to ship

def discounted_price(number_of_books):
    return(cover_price - (cover_price * .4)) # There is a 40% discount on wholesale book sales

def wholesale_cost(number_of_books):
    return ((discounted_price(number_of_books) * number_of_books) + ship_cost(number_of_books))

print("The cost of buying and shipping", number_of_books, "books is $",round(wholesale_cost(number_of_books), 2))

If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

Answer: 7:30 am

How I did it:

>>> start = (6*60+52)*60
>>> easy = (8*60+15)*2
>>> fast = (7*60+12)*3
>>> finish_hour = (start + easy + fast)/(60*60.0)
>>> finish_floored = (start + easy + fast)//(60*60)  #int() function can also be used to get integer value, but isn't taught yet.
>>> finish_minute  = (finish_hour - finish_floored)*60
>>> print ('Finish time was %d:%d' % (finish_hour,finish_minute))
Finish time was 7:30

*** ANOTHER WAY ***
start_time_hr = 6 + 52 / 60.0
easy_pace_hr = (8 + 15 / 60.0 ) / 60.0
tempo_pace_hr = (7 + 12 / 60.0) / 60.0
running_time_hr = 2 * easy_pace_hr + 3 * tempo_pace_hr
breakfast_hr = start_time_hr + running_time_hr
breakfast_min = (breakfast_hr-int(breakfast_hr))*60
breakfast_sec= (breakfast_min-int(breakfast_min))*60

print ('breakfast_hr', int(breakfast_hr) )
print ('breakfast_min', int (breakfast_min) )
print ('breakfast_sec', int (breakfast_sec) )
>>> 

Chapter 3[edit]

Exercise 3.1[edit]

Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

>>> def right_justify(s):
     print (' '*(70-len(s))+s)
 
>>> right_justify('allen')
                                                                 allen
>>> 

Alternate Solution Using concatenation and repetition

def right_justify(s):
    total_length = 70
    current_length = len(s)
    current_string = s
    while current_length < total_length:
       current_string = " " + current_string
       current_length = len(current_string)
    print(current_string)

OUTPUT

>>> right_justify("monty")
                                                                 monty

Exercise 3.3[edit]

You can see my solution at http://thinkpython.com/code/grid.py.

""" Solution to Exercise 3.5 on page 27 of Think Python Allen B. Downey, Version 1.1.24+Kart [Python 3.2] """ # here is a mostly-straightforward solution to the # two-by-two version of the grid. def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_beam(): print('+ - - - -', end='') def print_post(): print('| ', end='') def print_beams(): do_twice(print_beam) print('+') def print_posts(): do_twice(print_post) print('|') def print_row(): print_beams() do_twice(print_posts) def print_grid(): do_twice(print_row) print_beams() print_grid() ____________ # another solution def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_column(): print '+----+----+' def print_row(): print '| | |' def print_rows(): do_four(print_row) def do_block(): print_column() print_rows() def print_block(): do_twice(do_block) print_column() print_block() # nathan moses-gonzales _________ # straight-forward solution to 4x4 grid def do_twice(f): f() f() def do_four(f): # not needed for 2x2 grid do_twice(f) do_twice(f) def print_beam(): print('+----', end='') def print_post(): print('| ', end='') def print_beams(): do_twice(print_beam) print('+') def print_posts(): do_twice(print_post) print('|') def print_row(): print_beams() do_twice(print_posts) def print_grid2x2(): do_twice(print_row) print_beams() def print_beam4(): do_four(print_beam) print('+') def print_post4(): do_four(print_post) print('|') def print_row4(): print_beam4() do_twice(print_post4) def print_grid4x4(): do_four(print_row4) print_beam4() print_grid4x4() ----------------------- # here is a less-straightforward solution to the # four-by-four grid  def one_four_one(f, g, h): f() do_four(g) h() def print_plus(): print '+', def print_dash(): print '-', def print_bar(): print '|', def print_space(): print ' ', def print_end(): print def nothing(): "do nothing" def print1beam(): one_four_one(nothing, print_dash, print_plus) def print1post(): one_four_one(nothing, print_space, print_bar) def print4beams(): one_four_one(print_plus, print1beam, print_end) def print4posts(): one_four_one(print_bar, print1post, print_end) def print_row(): one_four_one(nothing, print4posts, print4beams) def print_grid(): one_four_one(print4beams, print_row, nothing) print_grid() comment = """ After writing a draft of the 4x4 grid, I noticed that many of the functions had the same structure: they would do something, do something else four times, and then do something else once. So I wrote one_four_one, which takes three functions as arguments; it calls the first one once, then uses do_four to call the second one four times, then calls the third. Then I rewrote print1beam, print1post, print4beams, print4posts, print_row and print_grid using one_four_one. Programming is an exploratory process. Writing a draft of a program often gives you insight into the problem, which might lead you to rewrite the code to reflect the structure of the solution. --- Allen """ print comment # another solution def beam(): plus = "+" minus = "-"*4 print(plus, minus, plus,minus, plus, minus, plus, minus, plus) def straight(): straight = "|" space = " "*4 print(straight, space, straight, space, straight, space, straight, space, straight, space) def quad_straight(): straight() straight() straight() straight() def twice(): beam() quad_straight() beam() quad_straight() def quad(): twice() twice() beam() quad() -- :) ------------------ # Without functions.  print("+ - - - - " * 2 + "+") print("|tt | tt|n" * 3 + "|tt | tt|") print("+ - - - - " * 2 + "+") print("|tt | tt|n " *3 + "|tt | tt|") print("+ - - - - " * 2 + "+") ------------------ Why not using the first solution and adapt it to the number of rows def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_column(): print '+----+----+----+----+' def print_row(): print '| | | | |' def print_rows(): do_four(print_row) def do_block(): print_column() print_rows() def print_block(): do_twice(do_block) # print_column() do_twice(do_block) print_column() print_block() ----------------------- # mteodor def draw_line(bar, middle = ' ', repeat = 2, lenght = 2): """ Draw a single line like this:  [ (B M*repeat)*lenght B]  """ for k in range(lenght): print("%s %s " % (bar, middle*repeat), end='') print(bar) def draw_grid(lenght = 2, height = 2, width = 2): """ Draw a grid like this:  + -- + -- +  | | |  | | |  + -- + -- +  | | |  | | |  + -- + -- +  where:  * lenght x heigth are the table size  * width is the size of a cell/column  """ for i in range(height): draw_line('+', '-', width, lenght) for j in range(lenght): draw_line('|', ' ', width, lenght) draw_line('+', '-', width, lenght) draw_grid(4, 4, 3) -------------------------- #kipp # auto adjust size of columns size=4 def beam(): print(" + - - - -"*size, "+") def post(): print(" | "*size, "|") def repeat(func): func() func() func() # manual adjust size for rows # this is 4 beam() repeat(post) beam() repeat(post) beam() repeat(post) beam() repeat(post) beam() 

Chapter 4[edit]

4.3 Exercise 1[edit]

from TurtleWorld import * world = TurtleWorld() bob = Turtle() def square(t): for i in range(4): fd(t, 100) lt(t) square(bob) wait_for_user() 

4.3 Exercise 2[edit]

from TurtleWorld import * world = TurtleWorld() bob = Turtle() print(bob) def square(t, length): t = Turtle() for i in range(4): fd(t, length) lt(t) square(bob, 200) wait_for_user() 

4.3 Exercise 3[edit]

from swampy.TurtleWorld import * world = TurtleWorld() bob = Turtle() print(bob) def polygon(t, length, n): for i in range(n): fd(t, length) lt(t, 360 / n) polygon(bob, 50, 8) wait_for_user() 

Chapter 5[edit]

Exercise 5.2[edit]

def countdown(a): # A typical countdown function if a < 0: print("Blastoff") elif a > 0: print(a) countdown(a - 1) def call_function(n,a): # The countdown function is called "n" number of times. Any other function can be used instead of countdown function. for i in range(n): countdown(a) call_function(3, 10) 

Exercise 5.3[edit]

Def is_triangle(a, b, c): if a <= b+c: if b <= a+c: if c <= a+b: return 'yes' else: return 'no' else: return 'no' else: return 'no' is_triangle(1, 12, 1) 'no' 

Exercise 5.3[edit]

Def is_triangle(a, b, c): if a<=b+c and b<=a+c and c<=a+b: return 'yes' else: return 'no' is_triangle(1, 12, 3) 'no' 

Chapter 9[edit]

Exercise 9.1[edit]

fin = open('words.txt') for line in fin: word = line.strip() if len(word) > 20: print (word) 

Exercise 9.2[edit]

fin = open('words.txt') def has_no_e(word): for char in word: if char in 'Ee': return False return True count = 0 for line in fin: word = line.strip() if has_no_e(word): count += 1 print (word) percent = (count / 113809.0) * 100 print (str(percent)) + "% of the words don't have an 'e'." 

Exercise 9.3[edit]

fin = open('words.txt') def avoids(word,letter): for char in word: if char in letter: return False return True letter = raw_input('What letters to exclude? ') count = 0 for line in fin: word = line.strip() if avoids(word, letter): count += 1 print word percent = (count / 113809.0) * 100 print str(percent) + "% of the words don't have " + letter + '.' 

Exercise 9.4[edit]

def uses_only(word, letters): """returns true if word is made only out of letters else flase""" for letter in word: if letter not in letters: return False return True 

Chapter 10[edit]

Exercise 10.1[edit]

Write a function called nested_sum that takes a nested list of integers and add up the elements from all of the nested lists.

def nested_sum(nestedList): '''  nestedList: list composed of nested lists containing int.  Returns the sum of all the int in the nested list  ''' newList = [] #Helper function to flatten the list def flatlist(nestedList): '''  Returns a flat list  ''' for i in range(len(nestedList)): if type(nestedList[i]) == int: newList.append(nestedList[i]) else: flatlist(nestedList[i]) return newList flatlist(nestedList) print sum(newList) nested_sum(nestedList) 

Exercise 10.2[edit]

Write a function named "capitalize_nested" that takes a nested list of strings and returns a new nested list with all strings capitalized.

>>> def capitalize_nested(l): def capitalize(s): return s.capitalize() for n, i in enumerate(l): if type(i) is list: l[n] = capitalize_nested(l[n]) elif type(i) is str: l[n] = capitalize(i) return l 

Exercise 10.3[edit]

Write a function that takes a list of numbers and returns the cumulative sum.

>>> def cumulative(l): cumulative_sum = 0 new_list = [] for i in l: cumulative_sum += i new_list.append(cumulative_sum) return new_list 

Exercise 10.4[edit]

Write a function called middle that takes a list and returns a new list that contains all but the first and last elements.

>>> def middle(x): res = [] i = 1 while i <= len(x)-2: res.append(x[i]) i += 1 return res 

This can also be done simply with a slice.

>>> def middle(x): return x[1:-1] 

Exercise 10.5[edit]

Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.

>>> def chop(x): del x[:1] del x[-1:] 

Chapter 11[edit]

Exercise 11.1[edit]

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

fin = open('words.txt') englishdict = dict() def create_diction(): counter = 0 dictionairy = dict() for line in fin: word = line.strip() dictionairy[word] = counter counter += 1 return dictionairy 

Exercise 11.2[edit]

def invert_dict(s): i={} for key in s: v=s[key] i.setdefault(v, []).append(key) return i 

Edit: This was not the exercise I found in my edition of 'Think Python', so I've added my answer in case anyone else is curious:
Use get to write histogram more concisely. You should be able to eliminate the if statement.

def histogram(s): d = dict() for c in s: d[c] = d.get(c,0)+1 return d 

Exercise 11.3[edit]

Dictionaries have a method called keys that returns the keys of the dictionary, in no particular order, as a list. Modify print_hist to print the keys and their values in alphabetical order.

v = {'p' : 1, 'a' : 1, 'r' : 2, 'o' : 1, 't' : 1} def print_hist(h): d = [] d += sorted(h.keys()) for c in d: print(c, h[c]) 

OR

v = {'p' : 1, 'a' : 1, 'r' : 2, 'o' : 1, 't' : 1} def print_hist(h): for c in sorted(h.keys()): print c, h[c] 

Exercise 11.4[edit]

Modify reverse_lookup so that it builds and returns a list of all keys that map to v, or an empty list if there are none.

def reverse_lookup(d,v): l = list() for c in d: if d[c] == v: l.append(c) return l 

Chapter 12[edit]

Exercise 12.1[edit]

numbers = (1,2,3) def sumall(numbers): x = 0 for i in numbers: x = x + i print x sumall(numbers) 

or

def sumall(*t): x = 0 for i in range(len(t)): x += t[i] return x 

or

def sumall(*args): t = list(args) return sum(t) 

or

def sumall(*args): return sum(args) 

Exercise 12.2[edit]

import random def sort_by_length(words): t = [] for word in words: t.append((len(word),word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) i=0 final = [] while i <= len(res)-2: if len(res[i]) == len(res[i+1]): y_list = [res[i], res[i+1]] random.shuffle(y_list) final = final + y_list i += 2 else: final.append(res[i]) i += 1 if i == len(res)-1: final.append(res[i]) return final 

or

from random import shuffle def sort_by_length(words): r = [] d = dict() for word in words: d.setdefault(len(word), []).append(word) for key in sorted(d, reverse=True): if len(d[key]) > 1: shuffle(d[key]) r.extend(d[key]) return r 

Exercise 12.3[edit]

import string def most_frequent(s): d = dict() inv = dict() for char in s: if char in string.ascii_letters: letter = char.lower() d[letter] = d.get(letter, 0) + 1 for letter, freq in d.items(): inv.setdefault(freq, []).append(letter) for freq in sorted(inv, reverse=True): print('{:.2%}:'.format(freq/(sum(list(inv)*len(inv[freq])))), ', '.join(inv[freq])) 

Chapter 13[edit]

Exercise 13.7[edit]

from string import punctuation, whitespace, digits from random import randint from bisect import bisect_left def process_file(filename): h = dict() fp = open(filename) for line in fp: process_line(line, h) return h def process_line(line, h): line = line.replace('-', ' ') for word in line.split(): word = word.strip(punctuation + whitespace + digits) word = word.lower() if word != '': h[word] = h.get(word, 0) + 1 hist = process_file('emma.txt') def cum_sum(list_of_numbers): cum_list = [] for i, elem in enumerate(list_of_numbers): if i == 0: cum_list.append(elem) else: cum_list.append(cum_list[i-1] + elem) return cum_list def random_word(h): word_list = list(h.keys()) num_list = [] for word in word_list: num_list.append(h[word]) cum_list = cum_sum(num_list) i = randint(1, cum_list[-1]) pos = bisect_left(cum_list, i) return word_list[pos] print(random_word(hist)) 

Chapter 14[edit]

Exercise 14.3[edit]

import shelve def dict_of_signatures_and_words(filename='words.txt'): d = dict() for line in open(filename): word = line.lower().strip() signature = ''.join(sorted(word)) d.setdefault(signature, []).append(word) return d def db_of_anagrams(filename='anagrams', d=dict_of_signatures_and_words()): db = shelve.open(filename) for key, values in d.items(): if len(values)>1: for index, value in enumerate(values): db[value]=values[:index]+values[index+1:] db.close() def print_contents_of_db(filename='anagrams'): db = shelve.open(filename, flag='r') for key in sorted(db): print(key.rjust(12), 't<==>t', ', '.join(db[key])) db.close() db_of_anagrams() print_contents_of_db() 

Exercise 14.5[edit]

# Replace urllib.request with urllib if you use Python 2. # I would love to see a more elegant solution for this exercise, possibly by someone who understands html. import urllib.request def check(zip_code): if zip_code == 'done': return False else: if len(zip_code) != 5: print('nThe zip code must have five digits!') return True def get_html(zip_code): gibberish = urllib.request.urlopen('http://www.uszip.com/zip/' + zip_code) less_gib = gibberish.read().decode('utf-8') return less_gib def extract_truth(code, key, delimiter): pos = code.find(key) + len(key) nearly_true = code[pos:pos+40] truth = nearly_true.split(delimiter)[0] return truth while True: zip_code = input('Please type a zip code (5 digits) or "done" if want to stop:n') if not check(zip_code): break code = get_html(zip_code) invalid_key = '(0 results)' if invalid_key in code: print('nNot a valid zip code.') continue name_key = ''</span> <span class="n">name_del</span> <span class="o">=</span> <span class="s1">' zip'</span> <span class="n">name</span> <span class="o">=</span> <span class="n">extract_truth</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">name_key</span><span class="p">,</span> <span class="n">name_del</span><span class="p">)</span> <span class="n">pop_key</span> <span class="o">=</span> <span class="s1">'Total population</dt><dd>'</span> <span class="n">pop_del</span> <span class="o">=</span> <span class="s1">'<'</span> <span class="n">pop</span> <span class="o">=</span> <span class="n">extract_truth</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">pop_key</span><span class="p">,</span> <span class="n">pop_del</span><span class="p">)</span> <span class="k">if</span> <span class="ow">not</span> <span class="mi">1</span> <span class="o"><</span> <span class="nb">len</span><span class="p">(</span><span class="n">pop</span><span class="p">)</span> <span class="o"><</span> <span class="mi">9</span><span class="p">:</span> <span class="n">pop</span> <span class="o">=</span> <span class="s1">'not available'</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="se">n</span><span class="s1">'</span> <span class="o">+</span> <span class="n">name</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Population:'</span><span class="p">,</span> <span class="n">pop</span><span class="p">,</span> <span class="s1">'</span><span class="se">n</span><span class="s1">'</span><span class="p">)</span> </pre></div><h2><span class="mw-headline" id="Chapter_15">Chapter 15</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="Exercise_15.1">Exercise 15.1</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="kn">import</span> <span class="nn">math</span> <span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">"""represents a point in 2-D space"""</span> <span class="k">def</span> <span class="nf">distance</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">):</span> <span class="n">distance</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">((</span><span class="n">p2</span><span class="o">.</span><span class="n">x</span> <span class="o">-</span> <span class="n">p1</span><span class="o">.</span><span class="n">x</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="p">(</span><span class="n">p2</span><span class="o">.</span><span class="n">y</span> <span class="o">-</span> <span class="n">p1</span><span class="o">.</span><span class="n">y</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="k">return</span> <span class="n">distance</span> <span class="n">p1</span> <span class="o">=</span> <span class="n">Point</span><span class="p">()</span> <span class="n">p2</span> <span class="o">=</span> <span class="n">Point</span><span class="p">()</span> <span class="n">p1</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">3</span> <span class="n">p1</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">2</span> <span class="n">p2</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">4</span> <span class="n">p2</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">3</span> <span class="nb">print</span><span class="p">(</span><span class="n">distance</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">))</span> </pre></div><h3><span class="mw-headline" id="Exercise_15.3">Exercise 15.3</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="kn">import</span> <span class="nn">copy</span> <span class="k">def</span> <span class="nf">move_rectangle</span><span class="p">(</span><span class="n">rec</span><span class="p">,</span> <span class="n">dx</span><span class="p">,</span> <span class="n">dy</span><span class="p">):</span> <span class="sd">""" does a deep copy and return the newRec with changes applied """</span> <span class="n">newRec</span> <span class="o">=</span> <span class="n">copy</span><span class="o">.</span><span class="n">deepcopy</span><span class="p">(</span><span class="n">rec</span><span class="p">)</span> <span class="n">newRec</span><span class="o">.</span><span class="n">corner</span><span class="o">.</span><span class="n">x</span> <span class="o">+=</span> <span class="n">dx</span> <span class="n">newRec</span><span class="o">.</span><span class="n">corner</span><span class="o">.</span><span class="n">y</span> <span class="o">+=</span> <span class="n">dy</span> <span class="k">return</span> <span class="n">newRec</span> </pre></div><h2><span class="mw-headline" id="Chapter_16">Chapter 16</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="Exercise_16.1">Exercise 16.1</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">def</span> <span class="nf">print_time</span><span class="p">(</span><span class="n">t</span><span class="p">):</span> <span class="nb">print</span> <span class="s1">'</span><span class="si">%.2d</span><span class="s1">:</span><span class="si">%.2d</span><span class="s1">:</span><span class="si">%.2d</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">t</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">t</span><span class="o">.</span><span class="n">second</span><span class="p">)</span> </pre></div><p>or
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># Solution for Python3</span> <span class="c1"># More on string formatting: http://docs.python.org/py3k/library/string.html#formatspec</span> <span class="k">def</span> <span class="nf">print_time</span><span class="p">(</span><span class="n">t</span><span class="p">):</span> <span class="c1"># 0 is a fill character, 2 defines the width</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{}</span><span class="s1">:</span><span class="si">{:02}</span><span class="s1">:</span><span class="si">{:02}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">t</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">t</span><span class="o">.</span><span class="n">second</span><span class="p">))</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.2">Exercise 16.2</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">def</span> <span class="nf">is_after</span><span class="p">(</span><span class="n">t1</span><span class="p">,</span> <span class="n">t2</span><span class="p">):</span> <span class="k">return</span> <span class="p">(</span><span class="n">t1</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">t1</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">t1</span><span class="o">.</span><span class="n">second</span><span class="p">)</span> <span class="o">></span> <span class="p">(</span><span class="n">t2</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">t2</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">t2</span><span class="o">.</span><span class="n">second</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.3">Exercise 16.3</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># Comment not by the author: This will give a wrong result, if (time.second + seconds % 60) > 60</span> <span class="k">def</span> <span class="nf">increment</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">seconds</span><span class="p">):</span> <span class="n">n</span> <span class="o">=</span> <span class="n">seconds</span><span class="o">/</span><span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">+=</span> <span class="n">seconds</span> <span class="o">-</span> <span class="mf">60.0</span><span class="o">*</span><span class="n">n</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">+=</span> <span class="n">n</span> <span class="n">m</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="o">/</span><span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">-=</span> <span class="n">m</span><span class="o">*</span><span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">+=</span> <span class="n">m</span> </pre></div><p>or
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># Solution for Python3</span> <span class="c1"># Replace '//' by '/' for Python2</span> <span class="k">def</span> <span class="nf">increment</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">seconds</span><span class="p">):</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">+=</span> <span class="n">seconds</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">+=</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span><span class="o">//</span><span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">+=</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="o">//</span><span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">%=</span> <span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">%=</span> <span class="mi">60</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">%=</span> <span class="mi">24</span> </pre></div><div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># A different way of going about it</span> <span class="k">def</span> <span class="nf">increment</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">seconds</span><span class="p">):</span> <span class="c1"># Converts total to seconds, then back to a readable format</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span><span class="o">*</span><span class="mi">3600</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="o">*</span><span class="mi">60</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">+</span> <span class="n">seconds</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span><span class="p">)</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">time_in_seconds</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="p">)</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.4">Exercise 16.4</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># Solution for Python3</span> <span class="c1"># Replace '//' by '/' for Python2</span> <span class="kn">from</span> <span class="nn">copy</span> <span class="kn">import</span> <span class="n">deepcopy</span> <span class="k">def</span> <span class="nf">increment</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">seconds</span><span class="p">):</span> <span class="n">r</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="n">time</span><span class="p">)</span> <span class="n">r</span><span class="o">.</span><span class="n">second</span> <span class="o">+=</span> <span class="n">seconds</span> <span class="n">r</span><span class="o">.</span><span class="n">minute</span> <span class="o">+=</span> <span class="n">r</span><span class="o">.</span><span class="n">second</span><span class="o">//</span><span class="mi">60</span> <span class="n">r</span><span class="o">.</span><span class="n">hour</span> <span class="o">+=</span> <span class="n">r</span><span class="o">.</span><span class="n">minute</span><span class="o">//</span><span class="mi">60</span> <span class="n">r</span><span class="o">.</span><span class="n">second</span> <span class="o">%=</span> <span class="mi">60</span> <span class="n">r</span><span class="o">.</span><span class="n">minute</span> <span class="o">%=</span> <span class="mi">60</span> <span class="n">r</span><span class="o">.</span><span class="n">hour</span> <span class="o">%=</span> <span class="mi">24</span> <span class="k">return</span> <span class="n">r</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.5">Exercise 16.5</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">class</span> <span class="nc">Time</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">"""represents the time of day.</span> <span class="sd"> attributes: hour, minute, second"""</span> <span class="n">time</span> <span class="o">=</span> <span class="n">Time</span><span class="p">()</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">=</span> <span class="mi">11</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">=</span> <span class="mi">59</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">=</span> <span class="mi">30</span> <span class="k">def</span> <span class="nf">time_to_int</span><span class="p">(</span><span class="n">time</span><span class="p">):</span> <span class="n">minutes</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="n">seconds</span> <span class="o">=</span> <span class="n">minutes</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="k">return</span> <span class="n">seconds</span> <span class="k">def</span> <span class="nf">int_to_time</span><span class="p">(</span><span class="n">seconds</span><span class="p">):</span> <span class="n">time</span> <span class="o">=</span> <span class="n">Time</span><span class="p">()</span> <span class="n">minutes</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">seconds</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">minutes</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="k">return</span> <span class="n">time</span> <span class="k">def</span> <span class="nf">increment</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">addtime</span><span class="p">):</span> <span class="n">seconds</span> <span class="o">=</span> <span class="n">time_to_int</span><span class="p">(</span><span class="n">time</span><span class="p">)</span> <span class="k">return</span> <span class="n">int_to_time</span><span class="p">(</span><span class="n">seconds</span> <span class="o">+</span> <span class="n">addtime</span><span class="p">)</span> <span class="k">def</span> <span class="nf">print_time</span> <span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="nb">print</span> <span class="s1">'The time is </span><span class="si">%.2d</span><span class="s1"> : </span><span class="si">%.2d</span><span class="s1"> : </span><span class="si">%.2d</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">second</span><span class="p">)</span> <span class="n">print_time</span> <span class="p">(</span><span class="n">time</span><span class="p">)</span> <span class="n">newtime</span> <span class="o">=</span> <span class="n">increment</span> <span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="mi">70</span><span class="p">)</span> <span class="n">print_time</span> <span class="p">(</span><span class="n">newtime</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.6">Exercise 16.6</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">def</span> <span class="nf">time_to_int</span><span class="p">(</span><span class="n">time</span><span class="p">):</span> <span class="n">minutes</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="n">seconds</span> <span class="o">=</span> <span class="n">minutes</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">+</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="k">return</span> <span class="n">seconds</span> <span class="k">def</span> <span class="nf">int_to_time</span><span class="p">(</span><span class="n">seconds</span><span class="p">):</span> <span class="n">time</span> <span class="o">=</span> <span class="n">Time</span><span class="p">()</span> <span class="n">minutes</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">second</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">seconds</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="n">time</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">minute</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">minutes</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="k">return</span> <span class="n">time</span> <span class="k">def</span> <span class="nf">mul_time</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">factor</span><span class="p">):</span> <span class="n">seconds</span> <span class="o">=</span> <span class="n">time_to_int</span><span class="p">(</span><span class="n">time</span><span class="p">)</span> <span class="n">seconds</span> <span class="o">*=</span> <span class="n">factor</span> <span class="n">seconds</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">seconds</span><span class="p">)</span> <span class="k">return</span> <span class="n">int_to_time</span><span class="p">(</span><span class="n">seconds</span><span class="p">)</span> <span class="k">def</span> <span class="nf">average_pace</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">distance</span><span class="p">):</span> <span class="k">return</span> <span class="n">mul_time</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="mi">1</span><span class="o">/</span><span class="n">distance</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.7">Exercise 16.7</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<p>Write a class definition for a Date object that has attributes <i>day</i>, <i>month</i> and <i>year</i>. Write a function called <i>increment_date</i> that takes a Date object, <i>date</i>, and an integer, <i>n</i>, and returns a new Date object that represents the day <i>n</i> days after <i>date</i>. Hint: “Thirty days hath September...” Challenge: does your function deal with leap years correctly? See <i>wikipedia.org/wiki/Leap_year</i>.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">class</span> <span class="nc">Date</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">"""represents a date.</span> <span class="sd"> attributes: day, month, year"""</span> <span class="k">def</span> <span class="nf">print_date</span><span class="p">(</span><span class="n">date</span><span class="p">):</span> <span class="c1"># German date format</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{}</span><span class="s1">.</span><span class="si">{}</span><span class="s1">.</span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">date</span><span class="o">.</span><span class="n">day</span><span class="p">,</span> <span class="n">date</span><span class="o">.</span><span class="n">month</span><span class="p">,</span> <span class="n">date</span><span class="o">.</span><span class="n">year</span><span class="p">))</span> <span class="k">def</span> <span class="nf">is_leap_year</span><span class="p">(</span><span class="n">year</span><span class="p">):</span> <span class="c1"># http://en.wikipedia.org/wiki/Leap_year#Algorithm</span> <span class="k">if</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">4</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="k">if</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">100</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="k">if</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">400</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">month_list</span><span class="p">(</span><span class="n">year</span><span class="p">):</span> <span class="k">if</span> <span class="n">is_leap_year</span><span class="p">(</span><span class="n">year</span><span class="p">):</span> <span class="k">return</span> <span class="p">[</span><span class="mi">31</span><span class="p">,</span> <span class="mi">29</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">]</span> <span class="k">return</span> <span class="p">[</span><span class="mi">31</span><span class="p">,</span> <span class="mi">28</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">31</span><span class="p">]</span> <span class="k">def</span> <span class="nf">days_of_year</span><span class="p">(</span><span class="n">year</span><span class="p">):</span> <span class="k">if</span> <span class="n">is_leap_year</span><span class="p">(</span><span class="n">year</span><span class="p">):</span> <span class="k">return</span> <span class="mi">366</span> <span class="k">return</span> <span class="mi">365</span> <span class="k">def</span> <span class="nf">date_to_int</span><span class="p">(</span><span class="n">date</span><span class="p">):</span> <span class="n">days</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">year</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">date</span><span class="o">.</span><span class="n">year</span><span class="p">):</span> <span class="n">days</span> <span class="o">+=</span> <span class="n">days_of_year</span><span class="p">(</span><span class="n">year</span><span class="p">)</span> <span class="n">month_days</span> <span class="o">=</span> <span class="n">month_list</span><span class="p">(</span><span class="n">date</span><span class="o">.</span><span class="n">year</span><span class="p">)</span> <span class="k">for</span> <span class="n">month</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">date</span><span class="o">.</span><span class="n">month</span><span class="p">):</span> <span class="n">days</span> <span class="o">+=</span> <span class="n">month_days</span><span class="p">[</span><span class="n">month</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]</span> <span class="n">days</span> <span class="o">+=</span> <span class="n">date</span><span class="o">.</span><span class="n">day</span> <span class="o">-</span> <span class="mi">1</span> <span class="k">return</span> <span class="n">days</span> <span class="k">def</span> <span class="nf">int_to_date</span><span class="p">(</span><span class="n">days</span><span class="p">):</span> <span class="n">date</span> <span class="o">=</span> <span class="n">Date</span><span class="p">()</span> <span class="n">date</span><span class="o">.</span><span class="n">year</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">next_days</span> <span class="o">=</span> <span class="mi">365</span> <span class="k">while</span> <span class="n">days</span> <span class="o">>=</span> <span class="n">next_days</span><span class="p">:</span> <span class="n">date</span><span class="o">.</span><span class="n">year</span> <span class="o">+=</span> <span class="mi">1</span> <span class="n">days</span> <span class="o">-=</span> <span class="n">next_days</span> <span class="n">next_days</span> <span class="o">=</span> <span class="n">days_of_year</span><span class="p">(</span><span class="n">date</span><span class="o">.</span><span class="n">year</span><span class="p">)</span> <span class="n">date</span><span class="o">.</span><span class="n">month</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">next_days</span> <span class="o">=</span> <span class="mi">31</span> <span class="n">month_days</span> <span class="o">=</span> <span class="n">month_list</span><span class="p">(</span><span class="n">date</span><span class="o">.</span><span class="n">year</span><span class="p">)</span> <span class="k">while</span> <span class="n">days</span> <span class="o">>=</span> <span class="n">next_days</span><span class="p">:</span> <span class="n">date</span><span class="o">.</span><span class="n">month</span> <span class="o">+=</span> <span class="mi">1</span> <span class="n">days</span> <span class="o">-=</span> <span class="n">next_days</span> <span class="n">next_days</span> <span class="o">=</span> <span class="n">month_days</span><span class="p">[</span><span class="n">date</span><span class="o">.</span><span class="n">month</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]</span> <span class="n">date</span><span class="o">.</span><span class="n">day</span> <span class="o">=</span> <span class="n">days</span> <span class="o">+</span> <span class="mi">1</span> <span class="k">return</span> <span class="n">date</span> <span class="k">def</span> <span class="nf">increment_date</span><span class="p">(</span><span class="n">date</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span> <span class="n">days</span> <span class="o">=</span> <span class="n">date_to_int</span><span class="p">(</span><span class="n">date</span><span class="p">)</span> <span class="k">return</span> <span class="n">int_to_date</span><span class="p">(</span><span class="n">days</span> <span class="o">+</span> <span class="n">n</span><span class="p">)</span> <span class="n">d1</span> <span class="o">=</span> <span class="n">Date</span><span class="p">()</span> <span class="n">d1</span><span class="o">.</span><span class="n">day</span><span class="p">,</span> <span class="n">d1</span><span class="o">.</span><span class="n">month</span><span class="p">,</span> <span class="n">d1</span><span class="o">.</span><span class="n">year</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2012</span> <span class="n">print_date</span><span class="p">(</span><span class="n">d1</span><span class="p">)</span> <span class="n">d2</span> <span class="o">=</span> <span class="n">increment_date</span><span class="p">(</span><span class="n">d1</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="n">print_date</span><span class="p">(</span><span class="n">d2</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="Exercise_16.8">Exercise 16.8</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<p>1. Use the <i>datetime</i> module to write a program that gets the current date and prints the day of the week.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span> <span class="k">def</span> <span class="nf">current_weekday</span><span class="p">():</span> <span class="n">i</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="nb">print</span> <span class="n">i</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">'%A'</span><span class="p">)</span> <span class="n">current_weekday</span><span class="p">()</span> </pre></div><p>2. Write a program that takes a birthday as input and prints the user’s age and the number of days, hours, minutes and seconds until their next birthday.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># Python3 solution. Replace "input" by "raw_input" for Python2.</span> <span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span> <span class="k">def</span> <span class="nf">time_until_birthday</span><span class="p">():</span> <span class="n">dob_input</span> <span class="o">=</span> <span class="nb">input</span><span class="p">((</span><span class="s1">'Please enter the date of your birth in '</span> <span class="s1">'the format "mm/dd/yyyy": '</span><span class="p">))</span> <span class="n">dob</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="n">dob_input</span><span class="p">,</span> <span class="s1">'%m/</span><span class="si">%d</span><span class="s1">/%Y'</span><span class="p">)</span> <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="k">if</span> <span class="n">now</span> <span class="o">></span> <span class="n">datetime</span><span class="p">(</span><span class="n">now</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="n">dob</span><span class="o">.</span><span class="n">month</span><span class="p">,</span> <span class="n">dob</span><span class="o">.</span><span class="n">day</span><span class="p">):</span> <span class="n">age</span> <span class="o">=</span> <span class="n">now</span><span class="o">.</span><span class="n">year</span> <span class="o">-</span> <span class="n">dob</span><span class="o">.</span><span class="n">year</span> <span class="n">next_year</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">else</span><span class="p">:</span> <span class="n">age</span> <span class="o">=</span> <span class="n">now</span><span class="o">.</span><span class="n">year</span> <span class="o">-</span> <span class="n">dob</span><span class="o">.</span><span class="n">year</span> <span class="o">-</span> <span class="mi">1</span> <span class="n">next_year</span> <span class="o">=</span> <span class="kc">False</span> <span class="n">time_to_birthday</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">now</span><span class="o">.</span><span class="n">year</span> <span class="o">+</span> <span class="n">next_year</span><span class="p">,</span> <span class="n">dob</span><span class="o">.</span><span class="n">month</span><span class="p">,</span> <span class="n">dob</span><span class="o">.</span><span class="n">day</span><span class="p">)</span> <span class="o">-</span> <span class="n">now</span> <span class="n">days</span> <span class="o">=</span> <span class="n">time_to_birthday</span><span class="o">.</span><span class="n">days</span> <span class="n">hours</span><span class="p">,</span> <span class="n">remainder</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">time_to_birthday</span><span class="o">.</span><span class="n">seconds</span><span class="p">,</span> <span class="mi">3600</span><span class="p">)</span> <span class="n">minutes</span><span class="p">,</span> <span class="n">seconds</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">remainder</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">n</span><span class="s2">You are </span><span class="si">{}</span><span class="s2"> years old."</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">age</span><span class="p">))</span> <span class="nb">print</span><span class="p">((</span><span class="s2">"You have </span><span class="si">{0}</span><span class="s2"> days, </span><span class="si">{1}</span><span class="s2"> hours, </span><span class="si">{2}</span><span class="s2"> minutes and </span><span class="si">{3}</span><span class="s2"> "</span> <span class="s2">"seconds left until your next birthday."</span><span class="p">)</span><span class="o">.</span><span class="n">format</span><span class="p">(</span> <span class="n">days</span><span class="p">,</span> <span class="n">hours</span><span class="p">,</span> <span class="n">minutes</span><span class="p">,</span> <span class="n">seconds</span><span class="p">))</span> <span class="n">time_until_birthday</span><span class="p">()</span> </pre></div><h2><span class="mw-headline" id="Chapter_17">Chapter 17</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="Exercise_17.8">Exercise 17.8</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<p>2.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="kn">from</span> <span class="nn">visual</span> <span class="kn">import</span> <span class="n">scene</span><span class="p">,</span> <span class="n">sphere</span> <span class="n">scene</span><span class="o">.</span><span class="n">range</span> <span class="o">=</span> <span class="p">(</span><span class="mi">256</span><span class="p">,</span> <span class="mi">256</span><span class="p">,</span> <span class="mi">256</span><span class="p">)</span> <span class="n">scene</span><span class="o">.</span><span class="n">center</span> <span class="o">=</span> <span class="p">(</span><span class="mi">128</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">128</span><span class="p">)</span> <span class="n">t</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">256</span><span class="p">,</span> <span class="mi">51</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">t</span><span class="p">:</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">t</span><span class="p">:</span> <span class="k">for</span> <span class="n">z</span> <span class="ow">in</span> <span class="n">t</span><span class="p">:</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="n">color</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span><span class="o">/</span><span class="mf">255.</span><span class="p">,</span> <span class="n">y</span><span class="o">/</span><span class="mf">255.</span><span class="p">,</span> <span class="n">z</span><span class="o">/</span><span class="mf">255.</span><span class="p">)</span> <span class="n">sphere</span><span class="p">(</span><span class="n">pos</span><span class="o">=</span><span class="n">pos</span><span class="p">,</span> <span class="n">radius</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="n">color</span><span class="p">)</span> </pre></div><p>3. Download http://thinkpython.com/code/color_list.py and use the function <i>read_colors</i> to generate a list of the available colors on your system, their names and RGB values. For each named color draw a sphere in the position that corresponds to its RGB values.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1"># As there currently (2013-04-12) is no function read_colors in color_list.py</span> <span class="c1"># I use a workaround and simply import the variable COLORS from color_list.py.</span> <span class="c1"># I then use the function all_colors() on COLORS to get a list of the colors.</span> <span class="kn">from</span> <span class="nn">color_list</span> <span class="kn">import</span> <span class="n">COLORS</span> <span class="kn">from</span> <span class="nn">visual</span> <span class="kn">import</span> <span class="n">scene</span><span class="p">,</span> <span class="n">sphere</span> <span class="k">def</span> <span class="nf">all_colors</span><span class="p">(</span><span class="n">colors_string</span><span class="o">=</span><span class="n">COLORS</span><span class="p">):</span> <span class="sd">"""Extract a list of unique RGB-tuples from COLORS.</span> <span class="sd"> The tuples look like (r, g, b), where r, g and b are each integers in</span> <span class="sd"> [0, 255].</span> <span class="sd"> """</span> <span class="c1"># split the string into lines and remove irrelevant lines</span> <span class="n">lines</span> <span class="o">=</span> <span class="n">colors_string</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">'</span><span class="se">n</span><span class="s1">'</span><span class="p">)[</span><span class="mi">2</span><span class="p">:</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># split the individual lines and remove the names</span> <span class="n">numbers_only</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">split</span><span class="p">()[:</span><span class="mi">3</span><span class="p">]</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">lines</span><span class="p">]</span> <span class="c1"># turn strings into ints and rgb-lists into tuples</span> <span class="n">rgb_tuples</span> <span class="o">=</span> <span class="p">[</span><span class="nb">tuple</span><span class="p">([</span><span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">])</span> <span class="k">for</span> <span class="n">lst</span> <span class="ow">in</span> <span class="n">numbers_only</span><span class="p">]</span> <span class="c1"># return a list of unique tuples</span> <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">rgb_tuples</span><span class="p">))</span> <span class="k">def</span> <span class="nf">make_spheres</span><span class="p">(</span><span class="n">color_tuples</span><span class="o">=</span><span class="n">all_colors</span><span class="p">()):</span> <span class="n">scene</span><span class="o">.</span><span class="n">range</span> <span class="o">=</span> <span class="p">(</span><span class="mi">256</span><span class="p">,</span> <span class="mi">256</span><span class="p">,</span> <span class="mi">256</span><span class="p">)</span> <span class="n">scene</span><span class="o">.</span><span class="n">center</span> <span class="o">=</span> <span class="p">(</span><span class="mi">128</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">128</span><span class="p">)</span> <span class="k">for</span> <span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">g</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="ow">in</span> <span class="n">color_tuples</span><span class="p">:</span> <span class="n">sphere</span><span class="p">(</span><span class="n">pos</span><span class="o">=</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">g</span><span class="p">,</span> <span class="n">b</span><span class="p">),</span> <span class="n">radius</span><span class="o">=</span><span class="mi">7</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="p">(</span><span class="n">r</span><span class="o">/</span><span class="mf">255.</span><span class="p">,</span> <span class="n">g</span><span class="o">/</span><span class="mf">255.</span><span class="p">,</span> <span class="n">b</span><span class="o">/</span><span class="mf">255.</span><span class="p">))</span> <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span> <span class="n">make_spheres</span><span class="p">()</span> </pre></div><h2><span class="mw-headline" id="Chapter_3.5">Chapter 3.5</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="calculator">calculator</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="c1">#recursion or recursive</span> <span class="nb">print</span> <span class="s2">"</span><span class="se">n</span><span class="s2"> INDEX</span><span class="se">n</span><span class="s2">""</span><span class="se">n</span><span class="s2"> C=1 for addition</span><span class="se">n</span><span class="s2">""</span><span class="se">n</span><span class="s2"> C=2 for substraction</span><span class="se">n</span><span class="s2">""</span><span class="se">n</span><span class="s2"> </span> <span class="n">C</span><span class="o">=</span><span class="mi">3</span> <span class="k">for</span> <span class="n">multiplication</span><span class="n">n</span><span class="s2">""</span><span class="n">n</span> <span class="n">C</span><span class="o">=</span><span class="mi">4</span> <span class="k">for</span> <span class="n">division</span><span class="n">n</span><span class="s2">""</span><span class="n">n</span> <span class="n">C</span><span class="o">=</span><span class="mi">5</span> <span class="k">for</span> <span class="n">to</span> <span class="n">find</span> <span class="n">modulus</span><span class="n">n</span><span class="s2">""</span><span class="n">n</span> <span class="n">C</span><span class="o">=</span><span class="mi">6</span> <span class="n">to</span> <span class="n">find</span> <span class="n">factorial</span><span class="n">n</span><span class="s2">"</span> <span class="n">C</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your choice here: "</span><span class="p">)</span> <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="n">c</span><span class="o">=</span><span class="n">x</span><span class="o">+</span><span class="n">y</span> <span class="nb">print</span> <span class="n">x</span><span class="p">,</span><span class="s2">"+"</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="s2">"="</span><span class="p">,</span><span class="n">c</span> <span class="k">def</span> <span class="nf">sub</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="n">c</span><span class="o">=</span><span class="n">x</span><span class="o">-</span><span class="n">y</span> <span class="nb">print</span> <span class="n">x</span><span class="p">,</span><span class="s2">"-"</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="s2">"="</span><span class="p">,</span><span class="n">c</span> <span class="k">def</span> <span class="nf">mul</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="n">c</span><span class="o">=</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="nb">print</span> <span class="n">x</span><span class="p">,</span><span class="s2">"*"</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="s2">"="</span><span class="p">,</span><span class="n">c</span> <span class="k">def</span> <span class="nf">div</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="n">c</span><span class="o">=</span><span class="n">x</span><span class="o">/</span><span class="n">y</span> <span class="nb">print</span> <span class="n">x</span><span class="p">,</span><span class="s2">"/"</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="s2">"="</span><span class="p">,</span><span class="n">c</span> <span class="k">def</span> <span class="nf">mod</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="n">c</span><span class="o">=</span><span class="n">x</span><span class="o">%</span><span class="n">y</span> <span class="nb">print</span> <span class="n">x</span><span class="p">,</span><span class="s2">"%"</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="s2">"="</span><span class="p">,</span><span class="n">c</span> <span class="k">if</span> <span class="n">C</span><span class="o">==</span><span class="mi">6</span><span class="p">:</span> <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="k">if</span> <span class="n">n</span><span class="o">==</span><span class="mi">1</span><span class="p">:</span> <span class="nb">print</span> <span class="n">n</span> <span class="k">return</span> <span class="n">n</span> <span class="k">else</span><span class="p">:</span> <span class="nb">print</span> <span class="n">n</span><span class="p">,</span><span class="s2">"*"</span><span class="p">,</span> <span class="k">return</span> <span class="n">n</span><span class="o">*</span><span class="n">f</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="n">n</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"enter your no here: "</span><span class="p">)</span> <span class="nb">print</span> <span class="n">f</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="k">if</span> <span class="n">C</span><span class="o">==</span><span class="mi">1</span><span class="p">:</span> <span class="n">a</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your first no here: "</span><span class="p">)</span> <span class="n">b</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your second no here: "</span><span class="p">)</span> <span class="n">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span> <span class="k">elif</span> <span class="n">C</span><span class="o">==</span><span class="mi">2</span><span class="p">:</span> <span class="n">a</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your first no here: "</span><span class="p">)</span> <span class="n">b</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your second no here: "</span><span class="p">)</span> <span class="n">sub</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span> <span class="k">elif</span> <span class="n">C</span><span class="o">==</span><span class="mi">3</span><span class="p">:</span> <span class="n">a</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your first no here: "</span><span class="p">)</span> <span class="n">b</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your second no here: "</span><span class="p">)</span> <span class="n">mul</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span> <span class="k">elif</span> <span class="n">C</span><span class="o">==</span><span class="mi">4</span><span class="p">:</span> <span class="n">a</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your first no here: "</span><span class="p">)</span> <span class="n">b</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your second no here: "</span><span class="p">)</span> <span class="n">div</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span> <span class="k">elif</span> <span class="n">C</span><span class="o">==</span><span class="mi">5</span><span class="p">:</span> <span class="n">a</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your first no here: "</span><span class="p">)</span> <span class="n">b</span><span class="o">=</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Enter your second no here: "</span><span class="p">)</span> <span class="n">mod</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="palindrome">palindrome</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">def</span> <span class="nf">first</span><span class="p">(</span><span class="n">word</span><span class="p">):</span> <span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">def</span> <span class="nf">last</span><span class="p">(</span><span class="n">word</span><span class="p">):</span><span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="k">def</span> <span class="nf">middle</span><span class="p">(</span><span class="n">word</span><span class="p">):</span> <span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="k">def</span> <span class="nf">palindrome</span><span class="p">(</span><span class="n">word</span><span class="p">):</span> <span class="k">if</span> <span class="n">first</span><span class="p">(</span><span class="n">word</span><span class="p">)</span><span class="o">==</span><span class="n">last</span><span class="p">(</span><span class="n">word</span><span class="p">):</span> <span class="n">word</span> <span class="o">=</span> <span class="n">middle</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="n">n</span><span class="o">=</span><span class="nb">len</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="k">if</span> <span class="n">n</span><span class="o"><</span><span class="mi">2</span><span class="p">:</span> <span class="nb">print</span> <span class="s2">"palindrome"</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">palindrome</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="nb">print</span> <span class="s2">"not palindrome"</span> <span class="n">word</span><span class="o">=</span><span class="n">raw_input</span><span class="p">(</span><span class="s2">"Enter the string:"</span><span class="p">)</span> <span class="n">palindrome</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> </pre></div><h3><span class="mw-headline" id="sum_of_all_digits">sum of all digits</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">def</span> <span class="nf">sum_of_n_numbers</span><span class="p">(</span><span class="n">number</span><span class="p">):</span> <span class="k">if</span><span class="p">(</span><span class="n">number</span><span class="o">==</span><span class="mi">0</span><span class="p">):</span> <span class="k">return</span> <span class="mi">0</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">number</span> <span class="o">+</span> <span class="n">sum_of_n_numbers</span><span class="p">(</span><span class="n">number</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="n">num</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">"Enter a number:"</span><span class="p">)</span> <span class="n">num</span><span class="o">=</span><span class="nb">int</span><span class="p">(</span><span class="n">num</span><span class="p">)</span> <span class="nb">sum</span> <span class="o">=</span> <span class="n">sum_of_n_numbers</span><span class="p">(</span><span class="n">num</span><span class="p">)</span> <span class="nb">print</span> <span class="nb">sum</span> <span class="c1">###another answer in case of while loops</span> <span class="k">def</span> <span class="nf">sum_of_Digits</span><span class="p">(</span><span class="n">number</span><span class="p">):</span> <span class="nb">sum</span><span class="o">=</span><span class="mi">0</span> <span class="k">while</span> <span class="n">number</span><span class="o">></span><span class="mi">0</span><span class="p">:</span> <span class="n">digit</span><span class="o">=</span><span class="n">number</span><span class="o">%</span><span class="mi">10</span> <span class="nb">sum</span><span class="o">=</span><span class="nb">sum</span><span class="o">+</span><span class="n">digit</span> <span class="n">number</span><span class="o">=</span><span class="n">number</span><span class="o">/</span><span class="mi">10</span> <span class="k">return</span> <span class="nb">sum</span> <span class="n">num</span><span class="o">=</span><span class="n">raw_input</span><span class="p">(</span><span class="s2">"enter the number"</span><span class="p">)</span> <span class="n">num</span><span class="o">=</span><span class="nb">int</span><span class="p">(</span><span class="n">num</span><span class="p">)</span> <span class="n">sum_of_digits</span><span class="o">=</span><span class="n">sum_of_Digits</span><span class="p">(</span><span class="n">num</span><span class="p">)</span> <span class="nb">print</span> <span class="n">sum_of_digits</span> </pre></div><h3><span class="mw-headline" id="Exercise_18.5">Exercise 18.5</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="k">class</span> <span class="nc">Card</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="n">suit_names</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'Clubs'</span><span class="p">,</span> <span class="s1">'Diamonds'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">,</span> <span class="s1">'Spades'</span><span class="p">]</span> <span class="n">rank_names</span> <span class="o">=</span> <span class="p">[</span><span class="kc">None</span><span class="p">,</span> <span class="s1">'Ace'</span><span class="p">,</span> <span class="s1">'2'</span><span class="p">,</span> <span class="s1">'3'</span><span class="p">,</span> <span class="s1">'4'</span><span class="p">,</span> <span class="s1">'5'</span><span class="p">,</span> <span class="s1">'6'</span><span class="p">,</span> <span class="s1">'7'</span><span class="p">,</span> <span class="s1">'8'</span><span class="p">,</span> <span class="s1">'9'</span><span class="p">,</span> <span class="s1">'10'</span><span class="p">,</span> <span class="s1">'Jack'</span><span class="p">,</span> <span class="s1">'Queen'</span><span class="p">,</span> <span class="s1">'King'</span><span class="p">]</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">suit</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">rank</span> <span class="o">=</span> <span class="mi">2</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">suit</span> <span class="o">=</span> <span class="n">suit</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank</span> <span class="o">=</span> <span class="n">rank</span> <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s1">'</span><span class="si">%s</span><span class="s1"> of </span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">Card</span><span class="o">.</span><span class="n">rank_names</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">rank</span><span class="p">],</span> <span class="n">Card</span><span class="o">.</span><span class="n">suit_names</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">suit</span><span class="p">])</span> <span class="k">def</span> <span class="nf">__cmp__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="n">c1</span> <span class="o">=</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">suit</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank</span><span class="p">)</span> <span class="n">c2</span> <span class="o">=</span> <span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">suit</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">rank</span><span class="p">)</span> <span class="k">return</span> <span class="nb">cmp</span><span class="p">(</span><span class="n">c1</span><span class="p">,</span> <span class="n">c2</span><span class="p">)</span> <span class="k">def</span> <span class="nf">is_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank</span> <span class="o">></span> <span class="mi">0</span> <span class="k">class</span> <span class="nc">Deck</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">'Deck'</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">label</span> <span class="o">=</span> <span class="n">label</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">):</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">14</span><span class="p">):</span> <span class="n">card</span> <span class="o">=</span> <span class="n">Card</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">k</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">card</span><span class="p">)</span> <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">res</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">card</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">:</span> <span class="n">res</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">card</span><span class="p">))</span> <span class="nb">print</span> <span class="bp">self</span><span class="o">.</span><span class="n">label</span> <span class="k">return</span> <span class="s1">'</span><span class="se">n</span><span class="s1">'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">res</span><span class="p">)</span> <span class="k">def</span> <span class="nf">deal_card</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="k">def</span> <span class="nf">add_card</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">card</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">card</span><span class="p">)</span> <span class="k">def</span> <span class="nf">shuffle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="kn">import</span> <span class="nn">random</span> <span class="n">random</span><span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">)</span> <span class="k">def</span> <span class="nf">sort</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="k">def</span> <span class="nf">move_cards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">,</span> <span class="n">num</span><span class="p">):</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num</span><span class="p">):</span> <span class="n">other</span><span class="o">.</span><span class="n">add_card</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">deal_card</span><span class="p">())</span> <span class="k">def</span> <span class="nf">deal_hands</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">num_hands</span><span class="p">,</span> <span class="n">num_cards</span><span class="p">):</span> <span class="k">if</span> <span class="n">num_hands</span><span class="o">*</span><span class="n">num_cards</span> <span class="o">></span> <span class="mi">52</span><span class="p">:</span> <span class="k">return</span> <span class="s1">'Not enough cards.'</span> <span class="n">l</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">num_hands</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span> <span class="n">hand_i</span> <span class="o">=</span> <span class="n">Hand</span><span class="p">(</span><span class="s1">'Hand </span><span class="si">%d</span><span class="s1">'</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">move_cards</span><span class="p">(</span><span class="n">hand_i</span><span class="p">,</span> <span class="n">num_cards</span><span class="p">)</span> <span class="n">l</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">hand_i</span><span class="p">)</span> <span class="k">return</span> <span class="n">l</span> <span class="k">class</span> <span class="nc">Hand</span><span class="p">(</span><span class="n">Deck</span><span class="p">):</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">''</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span> <span class="o">=</span> <span class="p">[]</span> <span class="bp">self</span><span class="o">.</span><span class="n">label</span> <span class="o">=</span> <span class="n">label</span> <span class="c1"># 18-6, 1-4:</span> <span class="k">class</span> <span class="nc">PokerHand</span><span class="p">(</span><span class="n">Hand</span><span class="p">):</span> <span class="k">def</span> <span class="nf">suit_hist</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">suits</span> <span class="o">=</span> <span class="p">{}</span> <span class="k">for</span> <span class="n">card</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">suits</span><span class="p">[</span><span class="n">card</span><span class="o">.</span><span class="n">suit</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">suits</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">card</span><span class="o">.</span><span class="n">suit</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">suits</span> <span class="k">def</span> <span class="nf">rank_hist</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span> <span class="o">=</span> <span class="p">{}</span> <span class="k">for</span> <span class="n">card</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="p">[</span><span class="n">card</span><span class="o">.</span><span class="n">rank</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">card</span><span class="o">.</span><span class="n">rank</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span> <span class="k">def</span> <span class="nf">P</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">values</span><span class="p">():</span> <span class="k">if</span> <span class="n">val</span> <span class="o">>=</span> <span class="mi">2</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">TP</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">values</span><span class="p">():</span> <span class="k">if</span> <span class="n">val</span> <span class="o">==</span> <span class="mi">4</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">elif</span> <span class="n">val</span> <span class="o">>=</span> <span class="mi">2</span> <span class="ow">and</span> <span class="n">val</span> <span class="o"><</span> <span class="mi">4</span><span class="p">:</span> <span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">return</span> <span class="n">count</span> <span class="o">>=</span> <span class="mi">2</span> <span class="k">def</span> <span class="nf">TOAK</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">values</span><span class="p">():</span> <span class="k">if</span> <span class="n">val</span> <span class="o">>=</span> <span class="mi">3</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">STRseq</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">seq</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">l</span> <span class="o">=</span> <span class="n">STRlist</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="n">h</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="n">h</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">h</span><span class="p">)</span> <span class="o"><</span> <span class="mi">5</span><span class="p">:</span> <span class="k">return</span> <span class="p">[]</span> <span class="c1"># Accounts for high Aces:</span> <span class="k">if</span> <span class="mi">1</span> <span class="ow">in</span> <span class="n">h</span><span class="p">:</span> <span class="n">h</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">h</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span> <span class="k">if</span> <span class="n">h</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">5</span><span class="p">:</span><span class="n">i</span><span class="p">]</span> <span class="ow">in</span> <span class="n">l</span><span class="p">:</span> <span class="n">seq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">h</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">5</span><span class="p">:</span><span class="n">i</span><span class="p">])</span> <span class="k">return</span> <span class="n">seq</span> <span class="k">def</span> <span class="nf">STR</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">seq</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">STRseq</span><span class="p">()</span> <span class="k">return</span> <span class="n">seq</span> <span class="o">!=</span> <span class="p">[]</span> <span class="k">def</span> <span class="nf">FL</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">suit_hist</span><span class="p">()</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">suits</span><span class="o">.</span><span class="n">values</span><span class="p">():</span> <span class="k">if</span> <span class="n">val</span> <span class="o">>=</span> <span class="mi">5</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">FH</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">d</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="n">keys</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span> <span class="k">if</span> <span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">>=</span> <span class="mi">3</span><span class="p">:</span> <span class="n">keys</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span> <span class="k">if</span> <span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">>=</span> <span class="mi">2</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">FOAK</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">rank_hist</span><span class="p">()</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">ranks</span><span class="o">.</span><span class="n">values</span><span class="p">():</span> <span class="k">if</span> <span class="n">val</span> <span class="o">>=</span> <span class="mi">4</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">SFL</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">seq</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">STRseq</span><span class="p">()</span> <span class="k">if</span> <span class="n">seq</span> <span class="o">==</span> <span class="p">[]:</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">for</span> <span class="nb">list</span> <span class="ow">in</span> <span class="n">seq</span><span class="p">:</span> <span class="n">list_suits</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">index</span> <span class="ow">in</span> <span class="nb">list</span><span class="p">:</span> <span class="k">for</span> <span class="n">card</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">:</span> <span class="k">if</span> <span class="n">card</span><span class="o">.</span><span class="n">rank</span> <span class="o">==</span> <span class="n">index</span><span class="p">:</span> <span class="n">list_suits</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">card</span><span class="o">.</span><span class="n">suit</span><span class="p">)</span> <span class="n">list_hist</span> <span class="o">=</span> <span class="n">histogram</span><span class="p">(</span><span class="n">list_suits</span><span class="p">)</span> <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">list_hist</span><span class="o">.</span><span class="n">keys</span><span class="p">():</span> <span class="k">if</span> <span class="n">list_hist</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">>=</span> <span class="mi">5</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">def</span> <span class="nf">classify</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">hands</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'Pair'</span><span class="p">,</span> <span class="s1">'Two-Pair'</span><span class="p">,</span> <span class="s1">'Three of a Kind'</span><span class="p">,</span> <span class="s1">'Straight'</span><span class="p">,</span> <span class="s1">'Flush'</span><span class="p">,</span> <span class="s1">'Full House'</span><span class="p">,</span> <span class="s1">'Four of a Kind'</span><span class="p">,</span> <span class="s1">'Straight Flush'</span><span class="p">]</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">P</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">TP</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">TOAK</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">STR</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">FL</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">FH</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">FOAK</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">SFL</span><span class="p">():</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">scores</span> <span class="o">!=</span> <span class="p">[]:</span> <span class="k">return</span> <span class="n">hands</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">scores</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="k">def</span> <span class="nf">STRlist</span><span class="p">():</span> <span class="n">s</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">9</span><span class="p">):</span> <span class="n">s</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">14</span><span class="p">)[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">5</span><span class="p">])</span> <span class="n">s</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="mi">10</span><span class="p">,</span><span class="mi">11</span><span class="p">,</span><span class="mi">12</span><span class="p">,</span><span class="mi">13</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span> <span class="k">return</span> <span class="n">s</span> <span class="k">def</span> <span class="nf">histogram</span><span class="p">(</span><span class="n">l</span><span class="p">):</span> <span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">()</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)):</span> <span class="n">d</span><span class="p">[</span><span class="n">l</span><span class="p">[</span><span class="n">k</span><span class="p">]]</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">l</span><span class="p">[</span><span class="n">k</span><span class="p">],</span><span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="n">d</span> <span class="c1"># 18-6, 5:</span> <span class="k">def</span> <span class="nf">p</span><span class="p">(</span><span class="n">config</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="n">trials</span> <span class="o">=</span> <span class="mi">10000</span><span class="p">,</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">1</span><span class="p">):</span> <span class="sd">"""Estimates probability that the</span> <span class="sd"> nth dealt hand will be config. A hand</span> <span class="sd"> consists of seven cards."""</span> <span class="n">successes</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">trials</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span> <span class="n">deck</span> <span class="o">=</span> <span class="n">Deck</span><span class="p">(</span><span class="s1">'Deck </span><span class="si">%d</span><span class="s1">'</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="n">deck</span><span class="o">.</span><span class="n">shuffle</span><span class="p">()</span> <span class="n">box</span> <span class="o">=</span> <span class="n">Hand</span><span class="p">()</span> <span class="n">deck</span><span class="o">.</span><span class="n">move_cards</span><span class="p">(</span><span class="n">box</span><span class="p">,</span> <span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">*</span><span class="mi">7</span><span class="p">)</span> <span class="n">hand</span> <span class="o">=</span> <span class="n">PokerHand</span><span class="p">(</span><span class="s1">'Poker Hand </span><span class="si">%d</span><span class="s1">'</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="n">deck</span><span class="o">.</span><span class="n">move_cards</span><span class="p">(</span><span class="n">hand</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="k">if</span> <span class="n">hand</span><span class="o">.</span><span class="n">classify</span><span class="p">()</span> <span class="o">==</span> <span class="n">config</span><span class="p">:</span> <span class="n">successes</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">return</span> <span class="mf">1.0</span><span class="o">*</span><span class="n">successes</span><span class="o">/</span><span class="n">trials</span> <span class="c1">#Iterate until first desired config.:</span> <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span> <span class="n">c</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span> <span class="n">deck</span> <span class="o">=</span> <span class="n">Deck</span><span class="p">()</span> <span class="n">deck</span><span class="o">.</span><span class="n">shuffle</span><span class="p">()</span> <span class="n">hand</span> <span class="o">=</span> <span class="n">PokerHand</span><span class="p">(</span><span class="s1">'Poker Hand </span><span class="si">%d</span><span class="s1">'</span> <span class="o">%</span> <span class="n">c</span><span class="p">)</span> <span class="n">deck</span><span class="o">.</span><span class="n">move_cards</span><span class="p">(</span><span class="n">hand</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="nb">print</span> <span class="n">hand</span> <span class="nb">print</span> <span class="n">hand</span><span class="o">.</span><span class="n">SFL</span><span class="p">()</span> <span class="k">if</span> <span class="n">hand</span><span class="o">.</span><span class="n">SFL</span><span class="p">():</span> <span class="nb">print</span> <span class="n">hand</span><span class="o">.</span><span class="n">STRseq</span><span class="p">()</span> <span class="k">break</span> <span class="nb">print</span> <span class="s1">''</span> <span class="n">c</span> <span class="o">+=</span> <span class="mi">1</span> <span class="n">Code</span> <span class="n">by</span> <span class="n">Victor</span> <span class="n">Alvarez</span> </pre></div><h2><span class="mw-headline" id="Appendix_B">Appendix B</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="Exercise_B.3">Exercise B.3</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>edit<span class="mw-editsection-bracket">]</span></span></h3>
<p>Write a function called <i>bisection</i> that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or <i>None</i> if it’s not.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"> <pre><span/><span class="kn">from</span> <span class="nn">bisect</span> <span class="kn">import</span> <span class="n">bisect_left</span> <span class="k">def</span> <span class="nf">bisection</span><span class="p">(</span><span class="n">sorted_list</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span> <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_left</span><span class="p">(</span><span class="n">sorted_list</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span> <span class="k">if</span> <span class="n">i</span> <span class="o"><</span> <span class="nb">len</span><span class="p">(</span><span class="n">sorted_list</span><span class="p">)</span> <span class="ow">and</span> <span class="n">sorted_list</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="n">item</span><span class="p">:</span> <span class="k">return</span> <span class="n">i</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="kc">None</span> <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span> <span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="nb">print</span><span class="p">(</span><span class="n">bisection</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="c1"># expect 1</span> <span class="n">b</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="nb">print</span><span class="p">(</span><span class="n">bisection</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="c1"># expect None</span> <span class="n">c</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span> <span class="nb">print</span><span class="p">(</span><span class="n">bisection</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="c1"># expect None</span> </pre></div><div> <table cellspacing="6" cellpadding="0"> <tbody> <tr> <td valign="top" align="left"> <p>Ackerman function, 6.11 </p> <ul> <li>AttributeError, 15.7, A.2.3</li> </ul> <ul> <li>absolute path, 14.4, 14.11</li> </ul> <p>histogram, 13.3 </p> <ul> <li>addition with carrying, 7.6</li> </ul> <ul> <li>algorithm, 1.2, 1.7, 7.6, 13.7</li> </ul> <p>Euclid, 6.11 </p> <ul> <li>aliasing, 10.10, 10.11, 10.14, 15.2, 15.6, 17.12</li> </ul> <p>copying to avoid, 10.13 </p> <ul> <li>alternative execution, 5.5</li> </ul> <ul> <li>append method, 10.6, 10.12, 10.15, 18.4, 18.6</li> </ul> <ul> <li>argument, 3.1, 3.5, 3.8, 3.8, 3.14, 10.12</li> </ul> <p>gather, 12.4 </p> <ul> <li>keyword, 4.5, 4.11, 12.7, 19.2</li> </ul> <ul> <li>optional, 8.8, 10.9, 11.3</li> </ul> <ul> <li>variable-length tuple, 12.4</li> </ul> <ul> <li>assignment, 2.11, 7.1, 10.1</li> </ul> <p>item, 8.5, 10.2, 12.1 </p> <ul> <li>tuple, 12.2, 12.3, 12.5, 12.10</li> </ul> <ul> <li>assignment statement, 2.2</li> </ul> <p>__dict__, 17.10 </p> <ul> <li>instance, 15.2, 15.8, 18.2, 18.10</li> </ul> <ul> <li>available colors, 15.9, 17.12</li> </ul> <ul> <li>Bangladesh, national flag, 15.9</li> </ul> <ul> <li>benchmarking, 13.9, 13.11</li> </ul> <ul> <li>big, hairy expression, A.3.2</li> </ul> <ul> <li>bisection, debugging by, 7.7</li> </ul> <ul> <li>body, 3.5, 3.14, 5.13, 7.3</li> </ul> <ul> <li>boolean expression, 5.2, 5.13</li> </ul> <ul> <li>boolean function, 6.4, 16.1</li> </ul> <ul> <li>borrowing, subtraction with, 7.6, 16.4</li> </ul> <ul> <li>bound method, 19.6, 19.10</li> </ul> <ul> <li>bounding box, 15.9, 19.4, 19.10</li> </ul> <p>squiggly, 11 </p> <ul> <li>bracket operator, 8.1, 10.2, 12.1</li> </ul> <p>worst, 17.12 </p> <ul> <li>Canvas coordinate, 19.3, 19.8</li> </ul> <ul> <li>Car Talk, 9.7, 9.7, 9.7, 11.10, 12.11</li> </ul> <ul> <li>Czech Republic, national flag, 15.9</li> </ul> <ul> <li>callback, 19.2, 19.6, 19.7, 19.8, 19.9, 19.10</li> </ul> <ul> <li>carrying, addition with, 7.6, 16.2, 16.4</li> </ul> <ul> <li>case-sensitivity, variable names, 2.10</li> </ul> <ul> <li>chained conditional, 5.6, 5.13</li> </ul> <p>Card, 18.1 </p> <ul> <li>class attribute, 18.2, 18.10</li> </ul> <ul> <li>class diagram, 18.8, 18.10</li> </ul> <ul> <li>close method, 14.2, 14.6, 14.8</li> </ul> <p>string, 8.10 </p> <ul> <li>composition, 3.4, 3.8, 3.14, 6.3, 18.4</li> </ul> <ul> <li>compound statement, 5.4, 5.13</li> </ul> <p>file, 14.8 </p> <ul> <li>concatenation, 2.8, 2.11, 3.9, 8.3, 8.5, 10.9</li> </ul> <p>list, 10.4, 10.12, 10.15 </p> <ul> <li>condition, 5.4, 5.13, 7.3, A.2.2</li> </ul> <p>chained, 5.6, 5.13 </p> <ul> <li>conditional execution, 5.4</li> </ul> <ul> <li>conditional operator, 18.3</li> </ul> <ul> <li>conditional statement, 5.4, 5.13, 6.4</li> </ul> <ul> <li>consistency check, 11.8, 16.4</li> </ul> <p>type, 3.2 </p> <p>Canvas, 19.3, 19.8 </p> <ul> <li>coordinate sequence, 19.4</li> </ul> <p>deep, 15.6 </p> <ul> <li>counter, 8.7, 8.12, 11.1, 11.6</li> </ul> <ul> <li>counting and looping, 8.7</li> </ul> <ul> <li>Doyle, Arthur Conan, 1.3.4</li> </ul> <ul> <li>DSU pattern, 12.7, 12.10, 13.4</li> </ul> <ul> <li>data structure, 12.9, 12.10, 13.9</li> </ul> <ul> <li>database, 14.6, 14.11, 14.12</li> </ul> <ul> <li>dead code, 6.1, 6.10, A.2.4</li> </ul> <ul> <li>debugging, 1.3, 1.3, 1.6, 1.7, 2.10, 3.13, 4.10, 5.12, 6.9, 8.11, 9.5, 10.13, 11.8, 12.9, 13.10, 14.10, 15.7, 16.5, 17.10, 18.9, 19.9, A</li> </ul> <p>by bisection, 7.7 </p> <ul> <li>emotional response, 1.6, A.3.4</li> </ul> <ul> <li>deck, playing cards, 18.4</li> </ul> <ul> <li>decorate-sort-undecorate pattern, 12.7</li> </ul> <ul> <li>default value, 13.5, 13.11, 17.5</li> </ul> <p>avoiding mutable, 17.12 </p> <p>circular, 6.5 </p> <ul> <li>deletion, element of list, 10.8</li> </ul> <ul> <li>deterministic, 13.2, 13.11</li> </ul> <p>encapsulation and generalization, 4.8 </p> <ul> <li>problem recognition, 9.3, 9.4</li> </ul> <ul> <li>prototype and patch, 16.2, 16.4</li> </ul> <ul> <li>random walk programming, 13.10, A.3.4</li> </ul> <p>call graph, 11.9 </p> <ul> <li>object, 15.2, 15.3, 15.6, 15.8, 16.1, 18.2</li> </ul> <ul> <li>state, 2.2, 7.1, 8.11, 10.2, 10.10, 10.11, 11.4, 12.6, 15.2, 15.3, 15.6, 16.1, 18.2</li> </ul> <ul> <li>__dict__ attribute, 17.10</li> </ul> <ul> <li>dictionary, 11, 11, 11.9, 12.6, A.2.3</li> </ul> <p>initialize, 12.6 </p> <p>anydbm module, 14.6 </p> <p>walk, 14.4 </p> <p>type-based, 17.9 </p> <ul> <li>dispatch, type-based, 17.8</li> </ul> <p>floating-point, 2.5 </p> <ul> <li>docstring, 4.9, 4.11, 15.1</li> </ul> <ul> <li>dot notation, 3.3, 3.14, 8.8, 15.2, 17.2, 18.2</li> </ul> <ul> <li>duplicate, 10.15, 10.15, 11.10, 14.12</li> </ul> <ul> <li>Euclid’s algorithm, 6.11</li> </ul> <ul> <li>embedded object, 15.3, 15.8, 17.12</li> </ul> <p>copying, 15.6 </p> <ul> <li>emotional debugging, 1.6, A.3.4</li> </ul> <ul> <li>encapsulation, 4.4, 4.11, 6.3, 7.5, 8.7, 18.7</li> </ul> <ul> <li>end of line character, 14.10</li> </ul> <ul> <li>equality and assignment, 7.1</li> </ul> <p>compile-time, A </p> <ul> <li>runtime, 1.3.2, 2.10, 5.10, 5.12, A</li> </ul> <ul> <li>semantic, 1.3.3, 2.1, 2.10, 8.11, A, A.3</li> </ul> <ul> <li>error message, 1.3.1, 1.3.3, 1.6, 2.1, 2.10, A.1</li> </ul> <ul> <li>event-driven programming, 19.2, 19.9, 19.10</li> </ul> <ul> <li>exception, 1.3.2, 1.7, 2.10, A, A.2.3</li> </ul> <p>AttributeError, 15.7, A.2.3 </p> <ul> <li>IndexError, 8.2, 8.11, 10.2, A.2.3</li> </ul> <ul> <li>TypeError, 8.1, 8.5, 11.4, 12.1, 12.4, 14.3, 17.3, A.2.3</li> </ul> <ul> <li>ValueError, 5.11, 11.3, 12.2</li> </ul> <ul> <li>exception, catching, 14.5</li> </ul> <ul> <li>experimental debugging, 1.3.4, 13.10</li> </ul> <ul> <li>expression, 2.5, 2.6, 2.11</li> </ul> <p>big and hairy, A.3.2 </p> <ul> <li>Fermat’s Last Theorem, 5.14</li> </ul> <ul> <li>Free Documentation License, GNU, 0, 0</li> </ul> <ul> <li>factorial function, 6.5, 6.8</li> </ul> <ul> <li>fibonacci function, 6.7, 11.5</li> </ul> <p>compression, 14.8 </p> <ul> <li>reading and writing, 14.2</li> </ul> <ul> <li>filter pattern, 10.7, 10.14</li> </ul> <ul> <li>floating-point, 2.11, 7.5</li> </ul> <ul> <li>floating-point division, 2.5</li> </ul> <ul> <li>floor division, 2.5, 2.11, 5.12</li> </ul> <ul> <li>flow of execution, 3.7, 3.14, 6.7, 6.9, 7.3, 18.9, 19.9, A.2.2</li> </ul> <ul> <li>for loop, 4.2, 8.3, 10.3, 12.5</li> </ul> <ul> <li>formal language, 1.4, 1.7</li> </ul> <ul> <li>format operator, 14.3, 14.11, A.2.3</li> </ul> <ul> <li>format sequence, 14.3, 14.11</li> </ul> <ul> <li>format string, 14.3, 14.11</li> </ul> <ul> <li>frame, 3.10, 3.14, 5.9, 6.5, 11.5</li> </ul> <p>letter, 12.11 </p> <ul> <li>fruitful function, 3.11, 3.14</li> </ul> <ul> <li>function, 3.5, 3.14, 17.1</li> </ul> <p>abs, 6.1 </p> <ul> <li>open, 9.1, 9.1, 14.2, 14.5, 14.6</li> </ul> <ul> <li>function composition, 6.3</li> </ul> <ul> <li>function definition, 3.5, 3.6, 3.14, 3.14</li> </ul> <ul> <li>function frame, 3.10, 3.14, 5.9, 11.5</li> </ul> <ul> <li>function object, 3.5, 3.15</li> </ul> <p>modifier, 16.3 </p> <ul> <li>function, reasons for, 3.12</li> </ul> <ul> <li>function, trigonometric, 3.3</li> </ul> <ul> <li>function, tuple as return value, 12.3</li> </ul> <ul> <li>functional programming style, 16.3, 16.6</li> </ul> <ul> <li>GCD (greatest common divisor), 6.11</li> </ul> <ul> <li>GNU Free Documentation License, 0, 0</li> </ul> <ul> <li>generalization, 4.5, 4.11, 9.3, 16.4</li> </ul> <ul> <li>geometry manager, 19.6, 19.10</li> </ul> <ul> <li>global variable, 11.6, 11.9</li> </ul> <p>update, 11.6 </p> <ul> <li>graphical user interface, 19.1</li> </ul> <ul> <li>greatest common divisor (GCD), 6.11</li> </ul> <ul> <li>guardian pattern, 6.8, 6.10, 8.11</li> </ul> <ul> <li>gzip (Unix command), 14.8</li> </ul> <ul> <li>HAS-A relationship, 18.8, 18.10</li> </ul> <ul> <li>hasattr function, 15.7, 17.10</li> </ul> <ul> <li>hash function, 11.4, 11.9</li> </ul> <ul> <li>hashable, 11.4, 11.9, 12.6</li> </ul> <ul> <li>high-level language, 1.1, 1.7</li> </ul> <ul> <li>histogram, 11.1, 11.1, 11.9</li> </ul> <p>random choice, 13.2, 13.7 </p> <ul> <li>IMDb (Internet Movie Database), 14.12</li> </ul> <ul> <li>IndexError, 8.2, 8.11, 10.2, A.2.3</li> </ul> <ul> <li>Internet Movie Database (IMDb), 14.12</li> </ul> <ul> <li>IS-A relationship, 18.8, 18.10</li> </ul> <ul> <li>immutability, 8.5, 8.5, 8.12, 10.11, 11.4, 12.1, 12.8</li> </ul> <ul> <li>implementation, 11.1, 11.9, 13.9</li> </ul> <ul> <li>import statement, 3.14, 4.1, 14.9</li> </ul> <ul> <li>in operator, 8.9, 9.3, 10.2, 11</li> </ul> <ul> <li>increment, 7.2, 7.8, 16.3, 17.3</li> </ul> <ul> <li>incremental development, 6.10, A.1</li> </ul> <ul> <li>indentation, 3.5, 17.2, A.1</li> </ul> <ul> <li>index, 8.1, 8.1, 8.11, 8.12, 10.2, 10.14, 11, A.2.3</li> </ul> <p>looping with, 9.4, 10.3 </p> <ul> <li>starting at zero, 8.1, 10.2</li> </ul> <ul> <li>infinite loop, 7.3, 7.8, 19.1, A.2.2, A.2.2</li> </ul> <ul> <li>infinite recursion, 5.10, 5.13, 6.8, A.2.2, A.2.2</li> </ul> <ul> <li>init method, 17.5, 17.10, 18.1, 18.4, 18.7</li> </ul> <ul> <li>initialization (before update), 7.2</li> </ul> <ul> <li>instance, 4.1, 4.11, 15.1, 15.8</li> </ul> <p>as argument, 15.2 </p> <ul> <li>instance attribute, 15.2, 15.8, 18.2, 18.10</li> </ul> <p>long, 11.7 </p> <ul> <li>interactive mode, 1.1, 1.7, 2.4, 3.11</li> </ul> <ul> <li>interface, 4.6, 4.10, 4.11, 18.9</li> </ul> <ul> <li>interlocking words, 10.15</li> </ul> <ul> <li>invariant, 16.5, 16.6, 19.9</li> </ul> <ul> <li>isinstance function, 6.8, 17.8</li> </ul> <p>Canvas, 19.3, 19.10 </p> <ul> <li>item assignment, 8.5, 10.2, 12.1</li> </ul> <ul> <li>key-value pair, 11, 11.9, 12.6</li> </ul> <ul> <li>keyword, 2.3, 2.3, 2.11, A.1</li> </ul> <p>def, 3.5 </p> <ul> <li>keyword argument, 4.5, 4.11, 12.7, 19.2, 19.10</li> </ul> <p>formal, 1.4 </p> <ul> <li>len function, 3.15, 8.2, 11</li> </ul> <ul> <li>letter rotation, 8.13, 11.10</li> </ul> <ul> <li>list, 10, 10.9, 10.14, 12.8</li> </ul> <p>as argument, 10.12 </p> <ul> <li>concatenation, 10.4, 10.12, 10.15</li> </ul> </td> <td valign="top" align="left"> <ul> <li>local variable, 3.9, 3.14</li> </ul> <ul> <li>logical operator, 5.2, 5.3</li> </ul> <ul> <li>loop, 4.2, 4.11, 7.3, 12.5</li> </ul> <p>condition, A.2.2 </p> <ul> <li>infinite, 7.3, 19.1, A.2.2</li> </ul> <p>with dictionaries, 11.2 </p> <ul> <li>looping and counting, 8.7</li> </ul> <ul> <li>looping with indices, 10.3</li> </ul> <ul> <li>low-level language, 1.1, 1.7</li> </ul> <ul> <li>Monty Python and the Holy Grail, 16.2</li> </ul> <ul> <li>mapping, 10.2, 10.14, 13.8</li> </ul> <p>bisection search, 10.15 </p> <ul> <li>metaphor, method invocation, 17.2</li> </ul> <ul> <li>method, 8.8, 8.12, 17.1, 17.11</li> </ul> <p>__cmp__, 18.3 </p> <ul> <li>append, 10.6, 10.12, 18.4, 18.6</li> </ul> <ul> <li>init, 17.5, 18.1, 18.4, 18.7</li> </ul> <ul> <li>sort, 10.6, 10.13, 12.7, 18.6</li> </ul> <ul> <li>method resolution order, 18.9</li> </ul> <p>anydbm, 14.6 </p> <ul> <li>random, 10.15, 12.7, 13.2, 18.6</li> </ul> <ul> <li>modulus operator, 5.1, 5.13</li> </ul> <ul> <li>multiline string, 4.9, A.1</li> </ul> <ul> <li>multiple assignment, 7.1, 7.8, 11.6</li> </ul> <ul> <li>multiplicity (in class diagram), 18.8, 18.10</li> </ul> <ul> <li>mutability, 8.5, 10.2, 10.5, 10.11, 11.6, 12.1, 12.8, 15.5</li> </ul> <ul> <li>mutable object, as default value, 17.12</li> </ul> <ul> <li>None special value, 3.11, 6.1, 6.10, 10.6, 10.8</li> </ul> <ul> <li>natural language, 1.4, 1.7</li> </ul> <ul> <li>nested conditional, 5.7, 5.13</li> </ul> <ul> <li>nested list, 10.1, 10.3, 10.14</li> </ul> <ul> <li>object, 8.5, 8.12, 10.10, 10.10, 10.14, 15.1</li> </ul> <p>Callable, 19.7 </p> <ul> <li>embedded, 15.3, 15.8, 17.12</li> </ul> <ul> <li>object diagram, 15.2, 15.3, 15.6, 15.8, 16.1, 18.2</li> </ul> <ul> <li>object-oriented language, 17.11</li> </ul> <ul> <li>object-oriented programming, 17.1, 17.11, 18.7</li> </ul> <ul> <li>open function, 9.1, 9.1, 14.2, 14.5, 14.6</li> </ul> <p>and, 5.3 </p> <ul> <li>format, 14.3, 14.11, A.2.3</li> </ul> <ul> <li>slice, 8.4, 8.13, 10.5, 10.12, 12.1</li> </ul> <ul> <li>operator overloading, 17.7, 18.3</li> </ul> <ul> <li>operator, arithmetic, 2.5</li> </ul> <ul> <li>optional argument, 8.8, 10.9, 11.3</li> </ul> <ul> <li>optional parameter, 13.5, 17.5</li> </ul> <ul> <li>order of operations, 2.7, 2.10, A.3.2</li> </ul> <ul> <li>other (parameter name), 17.4</li> </ul> <ul> <li>override, 13.5, 13.11, 17.5, 18.3, 18.7, 18.9</li> </ul> <ul> <li>PIL (Python Imaging Library), 19.11</li> </ul> <ul> <li>Puzzler, 9.7, 9.7, 9.7, 11.10, 12.11</li> </ul> <ul> <li>Python 3.0, 1.5, 2.5, 5.11, 11.7, 12.5</li> </ul> <ul> <li>Python debugger (pdb), A.2.3</li> </ul> <ul> <li>Python Imaging Library (PIL), 19.11</li> </ul> <ul> <li>packing widgets, 19.6, 19.10</li> </ul> <ul> <li>palindrome, 6.11, 8.13, 9.4, 9.7, 9.7</li> </ul> <ul> <li>parameter, 3.8, 3.9, 3.14, 10.12</li> </ul> <p>gather, 12.4 </p> <ul> <li>parent class, 18.7, 18.7, 18.10</li> </ul> <p>argument in, 3.1 </p> <ul> <li>overriding precedence, 2.7</li> </ul> <p>absolute, 14.4 </p> <p>DSU, 12.7, 13.4 </p> <ul> <li>decorate-sort-undecorate, 12.7</li> </ul> <ul> <li>guardian, 6.8, 6.10, 8.11</li> </ul> <ul> <li>search, 8.6, 8.12, 9.3, 11.3</li> </ul> <ul> <li>pdb (Python debugger), A.2.3</li> </ul> <ul> <li>pickle module, 14.1, 14.7</li> </ul> <ul> <li>plain text, 9.1, 13.1, 14.12, 19.11</li> </ul> <ul> <li>planned development, 16.4, 16.6</li> </ul> <ul> <li>playing card, Anglo-American, 18</li> </ul> <ul> <li>point, mathematical, 15.1</li> </ul> <ul> <li>polymorphism, 17.9, 17.11, 18.9</li> </ul> <ul> <li>postcondition, 4.10, 6.9, 18.9</li> </ul> <ul> <li>precondition, 4.10, 4.11, 4.11, 6.9, 10.15, 18.9</li> </ul> <ul> <li>print statement, 1.5, 1.7, 17.6, A.2.4</li> </ul> <ul> <li>problem recognition, 9.3, 9.4, 9.6</li> </ul> <ul> <li>programming language, 1.1</li> </ul> <ul> <li>prototype and patch, 16.2, 16.4, 16.6</li> </ul> <ul> <li>pseudorandom, 13.2, 13.11</li> </ul> <ul> <li>pure function, 16.2, 16.6</li> </ul> <ul> <li>quotation mark, 1.5, 2.1, 2.1, 4.9, 8.4, A.1</li> </ul> <ul> <li>Ramanujan, Srinivasa, 7.9</li> </ul> <ul> <li>raise statement, 11.3, 16.5</li> </ul> <ul> <li>randint function, 10.15, 13.2</li> </ul> <ul> <li>random function, 12.7, 13.2</li> </ul> <ul> <li>random module, 10.15, 12.7, 13.2, 18.6</li> </ul> <ul> <li>random walk programming, 13.10, A.3.4</li> </ul> <ul> <li>readline method, 9.1, 14.8</li> </ul> <ul> <li>recursion, 5.8, 5.8, 5.13, 6.5, 6.6</li> </ul> <p>base case, 5.9 </p> <ul> <li>infinite, 5.10, 6.8, A.2.2</li> </ul> <ul> <li>recursive definition, 6.5, 12.11</li> </ul> <ul> <li>reduce pattern, 10.7, 10.14</li> </ul> <ul> <li>reducible word, 11.10, 12.11</li> </ul> <ul> <li>reference, 10.11, 10.12, 10.14</li> </ul> <p>aliasing, 10.11 </p> <ul> <li>relative path, 14.4, 14.11</li> </ul> <ul> <li>reload function, 14.9, A.1.1</li> </ul> <p>list, 10.4 </p> <ul> <li>representation, 15.1, 15.3, 18.1</li> </ul> <ul> <li>return statement, 5.8, 6.1, A.3.3</li> </ul> <ul> <li>return value, 3.1, 3.14, 6.1, 15.4</li> </ul> <p>tuple, 12.3 </p> <ul> <li>reverse lookup, dictionary, 11.3, 11.9</li> </ul> <p>letters, 11.10 </p> <ul> <li>rules of precedence, 2.7, 2.11</li> </ul> <ul> <li>running pace, 1.8, 2.12, 16.7</li> </ul> <ul> <li>runtime error, 1.3.2, 2.10, 5.10, 5.12, A, A.2.3</li> </ul> <ul> <li>SimpleTurtleWorld class, 19.6</li> </ul> <ul> <li>Swampy, 4.1, 9.1, 15.9, 18.11, 19.1</li> </ul> <ul> <li>scaffolding, 6.2, 6.10, 11.8</li> </ul> <ul> <li>script mode, 1.1, 1.7, 2.4, 3.11</li> </ul> <ul> <li>search pattern, 8.6, 8.12, 9.3</li> </ul> <ul> <li>self (parameter name), 17.2</li> </ul> <ul> <li>semantic error, 1.3.3, 1.7, 2.1, 2.10, 8.11, A, A.3</li> </ul> <ul> <li>semantics, 1.3.3, 1.7, 17.1</li> </ul> <ul> <li>sequence, 8.1, 8.12, 10.1, 10.9, 12.1, 12.8</li> </ul> <p>coordinate, 19.4 </p> <p>anagram, 12.11, 14.7 </p> <ul> <li>shelve module, 14.7, 14.12</li> </ul> <ul> <li>singleton, 11.4, 11.9, 12.1</li> </ul> <p>copy, 8.4, 10.5 </p> <ul> <li>slice operator, 8.4, 8.13, 10.5, 10.12, 12.1</li> </ul> <ul> <li>sort method, 10.6, 10.13, 12.7, 18.6</li> </ul> <ul> <li>special case, 9.5, 9.6, 16.3</li> </ul> <p>False, 5.2 </p> <ul> <li>None, 3.11, 6.1, 6.10, 10.6, 10.8</li> </ul> <ul> <li>stack diagram, 3.10, 3.10, 3.14, 4.12, 5.9, 6.5, 6.11, 10.12</li> </ul> <ul> <li>state diagram, 2.2, 2.11, 7.1, 8.11, 10.2, 10.10, 10.11, 11.4, 12.6, 15.2, 15.3, 15.6, 16.1, 18.2</li> </ul> <p>assert, 16.5 </p> <ul> <li>conditional, 5.4, 5.13, 6.4</li> </ul> <ul> <li>print, 1.5, 1.7, 17.6, A.2.4</li> </ul> <ul> <li>__str__ method, 17.6, 18.5</li> </ul> <ul> <li>string, 2.1, 2.11, 10.9, 12.8</li> </ul> <p>accumulator, 18.5 </p> <ul> <li>string representation, 14.10, 17.6</li> </ul> <ul> <li>subject, 17.2, 17.11, 19.6</li> </ul> <p>dictionary, 13.6 </p> <ul> <li>subtraction with borrowing, 16.4</li> </ul> <ul> <li>superstitious debugging, A.3.4</li> </ul> <ul> <li>syntax, 1.3.1, 1.3.1, 1.7, 17.1, A.1</li> </ul> <ul> <li>syntax error, 1.3.1, 1.7, 2.10, A</li> </ul> <ul> <li>Turing complete language, 6.5</li> </ul> <ul> <li>TurtleWorld, 4.1, 5.14, 18.11</li> </ul> <ul> <li>TypeError, 8.1, 8.5, 11.4, 12.1, 12.4, 14.3, 17.3, A.2.3</li> </ul> <ul> <li>temporary variable, 6.1, 6.10, A.3.2</li> </ul> <ul> <li>test case, minimal, A.2.4</li> </ul> <p>and absence of bugs, 9.5 </p> <ul> <li>incremental development, 6.2</li> </ul> <p>plain, 9.1, 13.1, 14.12, 19.11 </p> <ul> <li>traceback, 3.10, 3.14, 5.10, 5.12, 11.3, A.2.3</li> </ul> <ul> <li>traversal, 8.3, 8.3, 8.6, 8.11, 8.12, 9.3, 9.3, 10.7, 10.14, 11.1, 11.2, 12.5, 12.5, 12.7, 13.3</li> </ul> <p>dictionary, 17.10 </p> <p>dictionary, 12.6 </p> <ul> <li>trigonometric function, 3.3</li> </ul> <ul> <li>triple-quoted string, 4.9</li> </ul> <ul> <li>tuple, 12.1, 12.3, 12.8, 12.10</li> </ul> <p>as key in dictionary, 12.6, 13.9 </p> <ul> <li>tuple assignment, 12.3, 12.5, 12.10</li> </ul> <p>bool, 5.2 </p> <ul> <li>type-based dispatch, 17.8, 17.9, 17.11</li> </ul> <ul> <li>typographical error, 13.10</li> </ul> <p>gzip, 14.8 </p> <ul> <li>underscore character, 2.3</li> </ul> <p>coordinate, 19.8 </p> <ul> <li>urllib module, 14.12, 19.11</li> </ul> <ul> <li>use before def, 2.10, 3.6</li> </ul> <ul> <li>user-defined type, 15.1, 16.1</li> </ul> <ul> <li>ValueError, 5.11, 11.3, 12.2</li> </ul> <ul> <li>value, 2.1, 2.11, 10.10, 10.10, 11.9</li> </ul> <p>default, 13.5 </p> <p>global, 11.6 </p> <ul> <li>temporary, 6.1, 6.10, A.3.2</li> </ul> <ul> <li>variable-length argument tuple, 12.4</li> </ul> <ul> <li>void function, 3.11, 3.14</li> </ul> <ul> <li>whitespace, 3.13, 5.12, 9.1, 14.10, A.1</li> </ul> <p>Button, 19.2 </p> <ul> <li>word frequency, 13.1, 13.12</li> </ul> <ul> <li>word, reducible, 11.10, 12.11</li> </ul> <p>ever, 19.11 </p> <ul> <li>zero, index starting at, 8.1, 10.2</li> </ul> <p>use with dict, 12.6 </p> </td> </tr> </tbody> </table> <hr/></div></div></div></div></div></div></div></div></div></div></td></div><div class='yarpp-related'> <h3>Related posts:</h3><ol> <li><a href="https://supercheats.site/python-programming-print-version-wikibooks-open-books-for-an-open-world/" rel="bookmark" title="Python Programming/Print version – Wikibooks, open books for an open world">Python Programming/Print version – Wikibooks, open books for an open world </a></li> <li><a href="https://supercheats.site/control-systems-digital-systems-print-version-wikibooks-open-books-for-an-open-world/" rel="bookmark" title="Control Systems/Digital Systems/Print version – Wikibooks, open books for an open world">Control Systems/Digital Systems/Print version – Wikibooks, open books for an open world </a></li> <li><a href="https://supercheats.site/a-level-computing-aqa-print-version-unit-2-wikibooks-open-books-for-an-open-world/" rel="bookmark" title="A-level Computing/AQA/Print version/Unit 2 – Wikibooks, open books for an open world">A-level Computing/AQA/Print version/Unit 2 – Wikibooks, open books for an open world </a></li> <li><a href="https://supercheats.site/principles-of-microeconomics-print-version-wikibooks-open-books-for-an-open-world/" rel="bookmark" title="Principles of Microeconomics/Print version – Wikibooks, open books for an open world">Principles of Microeconomics/Print version – Wikibooks, open books for an open world </a></li> </ol></div></div><footer class="entry-footer featured-desc">
<span class="cat-links"><i class="fa fa-folder-o"></i><a href="https://supercheats.site/category/game-news/" rel="category tag">Game news</a></span>	</footer>
</article>
<nav class="navigation post-navigation" role="navigation" aria-label="Posts">
<h2 class="screen-reader-text">Post navigation</h2>
<div class="nav-links"><div class="nav-previous"><a href="https://supercheats.site/xbox-video-games-with-gold-january-2021-free-video-games-revealed/" rel="prev">Xbox Video games With Gold January 2021 Free Video games Revealed</a></div><div class="nav-next"><a href="https://supercheats.site/10-extra-ignored-single-participant-indie-video-games-xboxone/" rel="next">10 Extra Ignored Single Participant Indie Video games : xboxone</a></div></div></nav>                <h2 class="widget-title">
Related posts                </h2>
<ul class="featured-entries-col featured-entries featured-col-posts featured-related-posts">
<li class="acme-col-3"> <figure class="widget-image"> <a href="https://supercheats.site/donkey-kong-nes-on-line-sport/"> <img onload="Wpfcll.r(this,true);" src="https://supercheats.site/wp-content/plugins/wp-fastest-cache-premium/pro/images/blank.gif" width="256" height="224" data-wpfc-original-src="https://supercheats.site/wp-content/uploads/2021/01/Donkey-Kong-NES-online-game.gif" class="attachment-large size-large wp-post-image" alt="Donkey Kong (NES) - online game"/> </a> </figure> <div class="featured-desc"> <div class="above-entry-meta"> <span> <a href="https://supercheats.site/2021/01/19/"> <i class="fa fa-calendar"></i> January 19, 2021 </a> </span> <span> <a href="https://supercheats.site/author/admin/" title="admin"> <i class="fa fa-user"></i> admin </a> </span> <span> <a href="https://supercheats.site/donkey-kong-nes-on-line-sport/#respond"><i class="fa fa-comment"></i>0</a> </span></div><a href="https://supercheats.site/donkey-kong-nes-on-line-sport/"> <h4 class="title"> Donkey Kong (NES) – on-line sport </h4> </a> <div class="details">           Sorry, however this sport isn’t abandonware and subsequently isn’t out...</div><div class="below-entry-meta"> <span class="cat-links"><a class="at-cat-item-48" href="https://supercheats.site/category/game-news/" rel="category tag">Game news</a> </span></div></div></li>
<li class="acme-col-3"> <figure class="widget-image"> <a href="https://supercheats.site/12-tribes-resort-on-line-casino-okanogan-okanogan-accommodations/"> <img onload="Wpfcll.r(this,true);" src="https://supercheats.site/wp-content/plugins/wp-fastest-cache-premium/pro/images/blank.gif" width="64" height="64" data-wpfc-original-src="https://supercheats.site/wp-content/uploads/2021/01/12-Tribes-Resort-Casino-Okanogan-Okanogan-Hotels.jpeg" class="attachment-large size-large wp-post-image" alt="12 Tribes Resort Casino Okanogan - Okanogan Hotels"/> </a> </figure> <div class="featured-desc"> <div class="above-entry-meta"> <span> <a href="https://supercheats.site/2021/01/19/"> <i class="fa fa-calendar"></i> January 19, 2021 </a> </span> <span> <a href="https://supercheats.site/author/admin/" title="admin"> <i class="fa fa-user"></i> admin </a> </span> <span> <a href="https://supercheats.site/12-tribes-resort-on-line-casino-okanogan-okanogan-accommodations/#respond"><i class="fa fa-comment"></i>0</a> </span></div><a href="https://supercheats.site/12-tribes-resort-on-line-casino-okanogan-okanogan-accommodations/"> <h4 class="title"> 12 Tribes Resort On line casino Okanogan – Okanogan Accommodations </h4> </a> <div class="details">Deluxe Room, 1 King Mattress 1 King Mattress Web – Free WiFi Leisure – 47-inch flat-screen...</div><div class="below-entry-meta"> <span class="cat-links"><a class="at-cat-item-48" href="https://supercheats.site/category/game-news/" rel="category tag">Game news</a> </span></div></div></li>
<li class="acme-col-3"> <figure class="widget-image"> <a href="https://supercheats.site/easy-methods-to-open-a-on-line-casino-and-begin-an-internet-gaming-enterprise/"> <img onload="Wpfcll.r(this,true);" src="https://supercheats.site/wp-content/plugins/wp-fastest-cache-premium/pro/images/blank.gif" width="640" height="192" data-wpfc-original-src="https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming-1024x307.jpg" class="attachment-large size-large wp-post-image" alt="online_open" data-wpfc-original-srcset="https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming-1024x307.jpg 1024w, https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming-300x90.jpg 300w, https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming-768x231.jpg 768w, https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming-1536x461.jpg 1536w, https://supercheats.site/wp-content/uploads/2021/01/How-to-open-a-casino-and-start-an-online-gaming.jpg 1672w" sizes="(max-width: 640px) 100vw, 640px"/> </a> </figure> <div class="featured-desc"> <div class="above-entry-meta"> <span> <a href="https://supercheats.site/2021/01/19/"> <i class="fa fa-calendar"></i> January 19, 2021 </a> </span> <span> <a href="https://supercheats.site/author/admin/" title="admin"> <i class="fa fa-user"></i> admin </a> </span> <span> <a href="https://supercheats.site/easy-methods-to-open-a-on-line-casino-and-begin-an-internet-gaming-enterprise/#respond"><i class="fa fa-comment"></i>0</a> </span></div><a href="https://supercheats.site/easy-methods-to-open-a-on-line-casino-and-begin-an-internet-gaming-enterprise/"> <h4 class="title"> Easy methods to open a on line casino and begin an internet gaming enterprise </h4> </a> <div class="details">On-line playing has all the time been probably the most profitable and fascinating areas to probe...</div><div class="below-entry-meta"> <span class="cat-links"><a class="at-cat-item-48" href="https://supercheats.site/category/game-news/" rel="category tag">Game news</a> </span></div></div></li>
</ul>
<div class="clearfix"></div><div id="comments" class="comments-area">
<div id="respond" class="comment-respond">
<h3 id="reply-title" class="comment-reply-title"><span></span> Leave a Comment <small><a rel="nofollow" id="cancel-comment-reply-link" href="/think-python-print-version-wikibooks-open-books-for-an-open-world/#respond" style="display:none;">Cancel reply</a></small></h3><form action="https://supercheats.site/wp-comments-post.php" method="post" id="commentform" class="comment-form"><p class="comment-form-comment"><label for="comment"></label> <textarea id="comment" name="comment" placeholder="Comment" cols="45" rows="8" aria-required="true"></textarea></p><p class="comment-form-author"><label for="author"></label><input id="author" name="author" type="text" placeholder="Name" value="" size="30" aria-required="true"/></p>
<p class="comment-form-email"><label for="email"></label> <input id="email" name="email" type="email" value="" placeholder="Email" size="30"aria-required="true"/></p>
<p class="comment-form-url"><label for="url"></label> <input id="url" name="url" placeholder="Website URL" type="url" value="" size="30" /></p>
<p class="comment-form-cookies-consent"><input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes" /> <label for="wp-comment-cookies-consent">Save my name, email, and website in this browser for the next time I comment.</label></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Add Comment" /> <input type='hidden' name='comment_post_ID' value='60887' id='comment_post_ID' />
<input type='hidden' name='comment_parent' id='comment_parent' value='0' />
</p></form></div></div></main></div><div id="secondary-right" class="widget-area sidebar secondary-sidebar float-right" role="complementary"> <div id="sidebar-section-top" class="widget-area sidebar clearfix"> <aside id="custom_html-2" class="widget_text widget widget_custom_html"><div class="textwidget custom-html-widget"> <p><a href="https://deckaffiliates.com/c/337039" target="_blank" rel="noopener noreferrer"><img onload="Wpfcll.r(this,true);" src="https://supercheats.site/wp-content/plugins/wp-fastest-cache-premium/pro/images/blank.gif" data-wpfc-original-src="https://supercheats.site/wp-content/uploads/2020/10/AchillesDeluxe_Belly_Art_800x600.png" alt="AchillesGames"></a></p></div></aside>		<aside id="recent-posts-2" class="widget widget_recent_entries">		<h3 class="widget-title"><span>Recent Posts</span></h3>		<ul>
<li> <a href="https://supercheats.site/donkey-kong-nes-on-line-sport/">Donkey Kong (NES) – on-line sport</a> </li>
<li> <a href="https://supercheats.site/12-tribes-resort-on-line-casino-okanogan-okanogan-accommodations/">12 Tribes Resort On line casino Okanogan – Okanogan Accommodations</a> </li>
<li> <a href="https://supercheats.site/easy-methods-to-open-a-on-line-casino-and-begin-an-internet-gaming-enterprise/">Easy methods to open a on line casino and begin an internet gaming enterprise</a> </li>
<li> <a href="https://supercheats.site/greenback-slots-on-line-slot-video-games-with-one-greenback-bets/">Greenback Slots – On-line Slot Video games with One Greenback Bets</a> </li>
<li> <a href="https://supercheats.site/superior-interactive-media-dvd-studio-professional/">Superior Interactive Media/DVD Studio Professional</a> </li>
<li> <a href="https://supercheats.site/tauronos-is-now-accessible-for-home-windows-10-xbox-one-and-xbox-sequence-xs-xbox-play-wherever/">TAURONOS Is Now Accessible For Home windows 10, Xbox One And Xbox Sequence X|S (Xbox Play Wherever)</a> </li>
<li> <a href="https://supercheats.site/on-line-casino-sizzling-pictures-gamble-on-line-at-these-main-on-line-playing-websites-casinos-the-place-you-may-play-for-actual-cash/">On line casino Sizzling Pictures | Gamble on-line at these main on-line playing websites & casinos the place you may play for actual cash</a> </li>
<li> <a href="https://supercheats.site/scot-blumstein-fb/">Scot Blumstein | Fb</a> </li>
<li> <a href="https://supercheats.site/hollywood-slots-on-line-play-get-free-spins-at-this-time/">Hollywood Slots On-line | Play & Get Free Spins At this time!</a> </li>
<li> <a href="https://supercheats.site/jackpot-capital-welcome-bonus-codes-free-spins-not-beneficial/">Jackpot Capital Welcome Bonus Codes & Free Spins – Not Beneficial</a> </li>
<li> <a href="https://supercheats.site/worms-armageddon-play-on-line/">WORMS ARMAGEDDON | Play On-line</a> </li>
<li> <a href="https://supercheats.site/%d0%be%d0%bd%d0%bb%d0%b0%d0%b9%d0%bd-%d0%ba%d0%b0%d0%b7%d0%b8%d0%bd%d0%be-%d0%bd%d0%b0-%d0%b3%d1%80%d0%b8%d0%b2%d0%bd%d1%8b-pointloto/">Онлайн казино на гривны PointLoto</a> </li>
<li> <a href="https://supercheats.site/life-bundle-youtubers-life-esports-life-tycoon-is-now-obtainable-for-xbox-one-and-xbox-collection-xs/">Life Bundle: Youtubers Life + Esports Life Tycoon Is Now Obtainable For Xbox One And Xbox Collection X|S</a> </li>
<li> <a href="https://supercheats.site/spiderman-video-games-on-line-spiderman-video-games-for-children/">Spiderman Video games On-line – Spiderman Video games for Children</a> </li>
<li> <a href="https://supercheats.site/methods-to-maximise-on-line-on-line-casino-free-spins-advantages/">Methods to Maximise On-line On line casino Free Spins Advantages</a> </li>
<li> <a href="https://supercheats.site/finest-odds-in-on-line-casino-operators/">Finest Odds in On line casino Operators</a> </li>
<li> <a href="https://supercheats.site/sizzling-shot-on-line-casino-slots-day-by-day-free-cash-collector/">Sizzling Shot On line casino Slots – Day by day Free Cash Collector</a> </li>
<li> <a href="https://supercheats.site/play-free-blackjack-on-line-right-here/">Play Free BlackJack On-line Right here</a> </li>
<li> <a href="https://supercheats.site/suzohapp-declares-separation-of-money-dealing-with-enterprise/">SUZOHAPP Declares Separation of Money Dealing with Enterprise</a> </li>
<li> <a href="https://supercheats.site/chess-opening-concept-1-e4-1-e5-2-nf3-2-nf6/">Chess Opening Concept/1. e4/1…e5/2. Nf3/2…Nf6</a> </li>
<li> <a href="https://supercheats.site/blender-3d-noob-to-pro-print-version/">Blender 3D: Noob to Pro/Print version</a> </li>
<li> <a href="https://supercheats.site/gme-dd-one-dd-to-rule-them-one-dd-to-search-out-them-one-dd-to-to-convey-all-of-them-and-within-the-darkness-bind-them-wallstreetbets/">(GME DD) One DD to rule them. One DD to search out them. One DD to to convey all of them and within the darkness bind them. : wallstreetbets</a> </li>
<li> <a href="https://supercheats.site/ruby-slots-on-line-casino/">Ruby Slots On line casino</a> </li>
<li> <a href="https://supercheats.site/poker-ace-finest-texas-holdem-poker-on-line-sport-aplikace-na-google-play/">Poker Ace – Finest Texas Holdem Poker On-line Sport – Aplikace na Google Play</a> </li>
<li> <a href="https://supercheats.site/betway-on-line-casino-evaluation-2021-desk-video-games-excessive-rtp-slots/">Betway On line casino Evaluation 2021 – Desk Video games & Excessive RTP Slots</a> </li>
</ul>
</aside><aside id="recent-comments-2" class="widget widget_recent_comments"><h3 class="widget-title"><span>Recent Comments</span></h3><ul id="recentcomments"><li class="recentcomments"><span class="comment-author-link">Ad Ul</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97489">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Sulimah Ibuku</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97488">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Sulimah Ibuku</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97487">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Sulimah Ibuku</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97486">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Allya Karunia</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97485">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Wazir 12</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97484">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">putri pertiwi</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97483">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">BALVAS1140</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97482">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Moch Fhany</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97481">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Angga Slamet</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97480">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Hendra bakti</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97479">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Umai Zakira</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97478">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Fhallisha Chubby</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97477">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">putri intan</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97476">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">perdatam terusan</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97475">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Zaid Tsabit</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97474">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Lily Salimah</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97473">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Tika Suzuki</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97472">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Fahri Gamerz</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97471">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Alby Lutfi</span> on <a href="https://supercheats.site/yuta-ke-pantai-pakai-mobil-alphard-lewat-kantor-polisi-sakura-college-recreation-wilson-kiddy/#comment-97470">Yuta Ke Pantai Pakai Mobil Alphard Lewat Kantor Polisi | Sakura College | Recreation Wilson Kiddy</a></li><li class="recentcomments"><span class="comment-author-link">Raja Arslan</span> on <a href="https://supercheats.site/singing-competitors-sport-present-aisay-chalay-ga-league-season-5-danish-taimoor-present-tiktok/#comment-97469">Singing Competitors | Sport Present Aisay Chalay Ga League Season 5 | Danish Taimoor Present | TikTok</a></li><li class="recentcomments"><span class="comment-author-link">Areeba Faizan</span> on <a href="https://supercheats.site/singing-competitors-sport-present-aisay-chalay-ga-league-season-5-danish-taimoor-present-tiktok/#comment-97468">Singing Competitors | Sport Present Aisay Chalay Ga League Season 5 | Danish Taimoor Present | TikTok</a></li><li class="recentcomments"><span class="comment-author-link">Shoaib Patoli</span> on <a href="https://supercheats.site/singing-competitors-sport-present-aisay-chalay-ga-league-season-5-danish-taimoor-present-tiktok/#comment-97467">Singing Competitors | Sport Present Aisay Chalay Ga League Season 5 | Danish Taimoor Present | TikTok</a></li><li class="recentcomments"><span class="comment-author-link">abida nazir</span> on <a href="https://supercheats.site/singing-competitors-sport-present-aisay-chalay-ga-league-season-5-danish-taimoor-present-tiktok/#comment-97466">Singing Competitors | Sport Present Aisay Chalay Ga League Season 5 | Danish Taimoor Present | TikTok</a></li><li class="recentcomments"><span class="comment-author-link">Silah Noor</span> on <a href="https://supercheats.site/singing-competitors-sport-present-aisay-chalay-ga-league-season-5-danish-taimoor-present-tiktok/#comment-97465">Singing Competitors | Sport Present Aisay Chalay Ga League Season 5 | Danish Taimoor Present | TikTok</a></li></ul></aside></div></div></div></div><div class="clearfix"></div><footer id="colophon" class="site-footer" role="contentinfo">
<div class="footer-wrapper"> <div class="top-bottom wrapper"> <div id="footer-top"> <div class="footer-columns"></div></div><div class="clearfix"></div></div><div class="wrapper footer-copyright border text-center"> <p> Copyright © All rights reserved </p> <div class="site-info"></div></div></div></footer></div><style>.yarpp-related{margin:1em 0;}
.yarpp-related a{text-decoration:none;font-weight:bold;}
.yarpp-related .yarpp-thumbnail-title{text-align:left;font-weight:bold;font-size:96%;text-decoration:none;}
.yarpp-related h3{font-weight:bold;padding:0 0 5px 0;font-size:125%;text-transform:capitalize;margin:0;}
.yarpp-related .yarpp-promote{clear:both;background:url(//api.engage.bidsystem.com/adk_mini_logo.png) no-repeat;float:right;text-indent:-1000px;cursor:pointer;color:#666;font-size:11px;height:17px;width:78px;}</style>
<noscript id="wpfc-google-fonts"><link rel='stylesheet' id='supermag-googleapis-css' href='//fonts.googleapis.com/css?family=Open+Sans%3A600%2C400%7CRoboto%3A300italic%2C400%2C500%2C700&ver=1.0.1' type='text/css' media='all'/>
</noscript>
<script>var click_object={"ajax_url":"https:\/\/supercheats.site\/wp-admin\/admin-ajax.php"};</script>
<script src='//supercheats.site/wp-content/cache/wpfc-minified/8n4q78wc/2t2ns.js' type="text/javascript"></script>
<!--[if lt IE 9]><script type='text/javascript' src='//supercheats.site/wp-content/cache/wpfc-minified/kwsrdz6w/2irzs.js'></script><![endif]-->
<!--[if lt IE 9]><script type='text/javascript' src='//supercheats.site/wp-content/cache/wpfc-minified/7821f2ht/2irzs.js'></script><![endif]-->
<script type="application/ld+json">{"@context":"http:\/\/schema.org\/","@type":"BlogPosting","mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/supercheats.site\/think-python-print-version-wikibooks-open-books-for-an-open-world\/"},"url":"https:\/\/supercheats.site\/think-python-print-version-wikibooks-open-books-for-an-open-world\/","headline":"Think Python\/Print version - Wikibooks, open books for an open...","datePublished":"2020-12-22T18:52:32+00:00","dateModified":"2020-12-22T18:52:32+00:00","publisher":{"@type":"Organization","@id":"https:\/\/supercheats.site\/#organization","name":"Super cheats","logo":{"@type":"ImageObject","url":"","width":600,"height":60}},"articleSection":"Game news","description":"A(M,N)={n+1if m=0A(m−1,1)if m>0 and n=0A(m−1,A(m,n−1))if m>0 and n>0{displaystyle A(M,N)={begin{cases}n+1&{mbox{if }}m=0\\A(m-1,1)&{mbox{if }}m>0{mbox{ and }}n=0\\A(m-1,A(m,n-1))&{mbox{if }}m>0{mbox{ and }}n>0end{cases}}} Write a function named 'ack' that evaluates Ackerman’s function. Use your function to evaluate 'ack(3, 4)', which should be 125. What happens for larger values of 'm' and 'n'? Exercise 6 A palindrome is a word that is spelled the","author":{"@type":"Person","name":"admin","url":"https:\/\/supercheats.site\/author\/admin\/","image":{"@type":"ImageObject","url":"https:\/\/secure.gravatar.com\/avatar\/79845a49b7f85bbe16ae7e5d65d7fd6f?s=96&d=mm&r=g","height":96,"width":96},"sameAs":["https:\/\/supercheats.site"]}}</script>
<script defer src='//supercheats.site/wp-content/cache/wpfc-minified/qkwku3ol/g0ucy.js' type="text/javascript"></script>
<script>document.addEventListener('DOMContentLoaded',function(){function wpfcgl(){var wgh=document.querySelector('noscript#wpfc-google-fonts').innerText, wgha=wgh.match(/<link[^\>]+>/gi);for(i=0;i<wgha.length;i++){var wrpr=document.createElement('div');wrpr.innerHTML=wgha[i];document.body.appendChild(wrpr.firstChild);}}wpfcgl();});</script>
</body>
</html><!-- WP Fastest Cache file was created in 4.3216378688812 seconds, on 19-01-21 2:51:06 --><!-- need to refresh to see cached version --><script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>