Litvin Python Chapter 04
Litvin Python Chapter 04
Programming
in Python
>>> Second Edition:
with Python 3
Maria Litvin
Phillips Academy, Andover, Massachusetts
Gary Litvin
Skylight Software, Inc.
Skylight Publishing
Andover, Massachusetts
Skylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810
web:
e-mail:
http://www.skylit.com
[email protected]
[email protected]
1 2 3 4 5 6 7 8 9 10
15 14 13 12 11 10
a1 , a2 , ..., an , ...
or
b0 , b1 , ..., bn , ...
simply: Consider a sequence {an = 2n n} . The n-th term formula is called the
57
58
the Internet, at
It is called The
On-Line Encyclopedia of Integer Sequences. The database contains over 100,000
interesting sequences (that is, sequences that came up in one mathematical problem
or another). About 10,000 new interesting sequences arrive every year.
We say that a sequence converges to a certain number (called the limit of the
sequence) if its terms get closer and closer to that number as n increases. For
1
( 1) n
example, an = n converges to 0; an = n also converges to 0. The sequence
2
2
1, 1, 1, 1, 1, ... bounces around zero but does not converge to any limit;
1, 2, 4, 8, 16, ... does not converge because its terms get bigger and bigger as n
increases. When a sequence does not converge, we say that it diverges.
Example 1
1, 3, 5, ..., 2n 1, ... ( d = 2 ) and 5, 15, 25, ..., 5 + 10(n 1), ... ( d = 10 ) are both
arithmetic sequences.
59
c, cr , cr 2 , ..., cr n 1 , ... . The constant r is called the common ratio. The general term
of a geometric sequence can be written as an = cr n 1
Example 2
1 1 1 1
, , , , ... are examples of geometric sequences.
2 4 8 16
The concepts of arithmetic and geometric sequences are related to the concepts of the
arithmetic and geometric mean (see Questions 7 and 8). The arithmetic mean (the
a+b
. The geometric mean of two
average) of two numbers a and b is defined as
2
positive numbers a and b is defined as ab . Figure 4-1 gives a neat geometric
interpretation of the arithmetic and geometric mean and demonstrates that the
geometric mean never exceeds the arithmetic mean.
R=
a
a+b
; h = ab
2
Exercises
1.
Come up with your own interesting sequence, defined in words. State its
n-th term.
60
2.
3.
4.
Suppose the first term of an arithmetic sequence is 3 and the 7th term is 21.
Find the 12th term. 3
5.
What is the common ratio of the geometric sequence 4, 12, 36, ... ? What is
its general term?
6.
Suppose the first term of a geometric sequence is 1 and the 11th term is
1024. Find the 21st term.
7.
Show that in an arithmetic sequence, each term (except the first) is the
a + an +1
arithmetic mean of its left and right neighbors, that is, an = n 1
.
2
8.
Show that in a geometric sequence with positive terms, each term (except the
first) is the geometric mean of its left and right neighbors, that is,
an = an 1an +1 .
9.
Are there any sequences that are arithmetic and geometric at the same
time? 3
10.
11.
n 2
12.
n
What is the limit of the sequence an =
?
n 2 1
1 2 3 4
, , , , ... ? 3
2 3 4 5
61
4.3 ~ SUMS
4.3 Sums
In many mathematical situations we are interested in the sum of the first n terms of a
n(n + 1)
. A more
sequence. We have already seen in Chapter 1 that 1 + 2 + ... + n =
2
interesting example is 13 + 23 + 33 + ... + n3 . With a little algebraic technique it is
n(n + 1)
fairly easy to show that this sum is equal to
.
2
2
In other words,
a .
i =1
is the letter sigma of the Greek alphabet, written in the upper case. i is a variable
you can use j, k, or any other symbol. So we can write the sum of the first ten
10
cubes as
. The above identity that involves the sum of the first n cubes can be
k =1
n
restated as k = k .
k =1
k =1
n
Example 1
The sum of a geometric sequence
Lets start with a simple geometric sequence: 1, 2, 4,..., 2n1 ,... . We want to find the
sum of the first n terms of this sequence:
sn = 1 + 2 + 4 + ... + 2n 1
62
2sn = 2 + 4 + 8 + ... + 2n 1 + 2n
a very similar sum, with almost the same terms, except the first term is missing
and 2n is added on the right. If we subtract the first sum from the second, the same
terms will cancel out, and we will be left with 2sn sn = sn = 2n 1 .
is another way to prove that 1 + 2 + 4 + ... + 2 = 2 1 . We know that the
There
formula works for n = 0: 1 = 1. Lets assume that for any given n, the formula works
n 1
so the formula works for n, too. From this we can conclude that the formula works
for any n 1 . This method of proof is called mathematical induction; more on it in
Chapter 11.
Exercises
1.
n(n + 1)
,
2
1+ n
, times the number of
2
terms n. Show that the same is true for any arithmetic sequence.
2.
Derive the formula for the sum of the first n terms of the arithmetic sequence
n
[a
i =1
Question 1. Hint:
c = nc ;
i =1
3.
i =1
i =1
[(i 1)d ] = d (i 1) .
Find the sum of the the first n terms of the telescopic sequence
1
1
1
1
1
1 1
+
+
+ ... +
. Hint:
= , for example. 3
7 8 7 8
1 2 2 3 3 4
n (n + 1)
4.
63
1 1
1
1
+ + ... + n = 1 n . Hint: take a square pizza,
2 4
2
2
1 by 1 foot. Cut it in half. Cut one of the pieces in half. Cut one of the new
pieces in half. Keep cutting...
Show graphically that
5.
6.
Find
d 10
. 3
d =1
(2
n
7.
Find
k =1
8.
k) .
Derive a formula for 12 + 22 + ... + n 2 . Hint: look for the formula in the
form An3 + Bn 2 + Cn + D ; plug in n = 0, n = 1, n = 2, n = 3 to find A, B, C,
and D.
64
Here sn is a normal finite sum, for any particular n. It is called a partial sum of the
series.
If the sequence of partial sums converges to a number, that number is
called the sum of the series. In that case, it is said that the series
converges.
You may still be not quite convinced: how can a sequence of partial sums ever
converge? Arent we adding more and more terms to the sum? But it is possible for
the sums to converge if we add smaller and smaller amounts.
Example 1
1 1
1
1 1
1
1
+ + ... + n + ... , sn = + + ... + n = 1 n . As n
2 4
2
2 4
2
2
1
increases, sn approaches 1 (because n approaches 0). The partial sums never quite
2
reach 1, but they get closer and closer to 1 as n increases, and the sum of the whole
series is said to be 1.
a
i =1
2
i =1
or
b
k =0
. is the
=1.
For a series to converge, its terms must be getting smaller and smaller,
converging to 0.
Is the converse true? That is, if the terms of a series get smaller and smaller,
approaching 0, then does the series necessarily converge? It turns out this is not true.
65
Example 2
1 1 1
1
+ + + ... + + ... is called the harmonic series. Let us show that
2 3 4
n
the harmonic series diverges. The idea is to split it into non-overlapping finite
1
segments such that the sum of each segment exceeds a fixed number ( , for
2
example). Here is the way to do it:
The series 1 +
1 1
=
2 2
1 1 1 1 2 1
+ > + = =
3 4 4 4 4 2
1 1 1 1 1 1 1 1 4 1
+ + + > + + + = =
5 6 7 8 8 8 8 8 8 2
1 1
1
1 1
1
8 1
+ + ... + > + + ... + = =
9 10
16 16
16
16 16 2
8 times
...
And so on. The segments get longer and longer, but we dont care: we have an
infinite supply of terms to play with! So we can find a partial sum of this series that
1 1
1
is greater than + + ... + , for any k, and therefore the harmonic series cannot
2
2
2
k times
converge.
Figure 4-2 shows an odd construction based on the harmonic series. The tower rests
on one brick and extends to the right as far as we want without any other support!
1
You can keep adding bricks at the bottom, with the displacement . It is not very
n
hard to show that, for any n > 1, the center of gravity of the top n bricks falls on the
border of the (n + 1)-th brick.
66
1 1 1
6 5 4
1
3
1
2
Example 3
The series 1 +
1 1 1
1
+ + + ... + 2 + ... converges. Moreover, its sum is a surprise:
4 9 16
n
. It seems pops up here out of the blue, but there is a deep mathematical
6
connection.
In general, the series is a fascinating topic that reveals many beautiful mathematical
facts. Series are studied in Calculus, whose powerful methods help tell whether a
particular series converges or not.
Exercises
1.
1
1
1
1
+
+
+ ... +
+ ... .
1 2 2 3 3 4
n (n + 1)
Hint: see Question 3 in Section 4.3.
2.
n =1
sum? 3
n +1
100n
67
3.
dn
10
n=0
5.
1 1
1
Does the series 1 + + + ... +
+ ... converge? Explain your reasoning.
3 5
2n 1
6.
n =1
7.
68
Python supports int and float types of numbers. (It also supports the complex
type, but we will leave this alone for now.) Python has +, -, *, and / operators.
When +, -, and * are applied to two ints, the result is an int (as long as the result
stays within the int range). If at least one of the operands is a float, the result is a
float. The division operator /, when applied to two integers, gives a float.
Python has another division operator, //. When // is applied to two integers, a and
a
b, the result is the largest integer that does not exceed . For example, 15//2 gives
b
7, -15/2 gives -8.
For your convenience, Python also has the augmented assignment operators +=, -=,
*=, and so on. a += b is the same as a = a + b; a -= b is the same as
a = a - b, and so on.
Our program should print n and the sum 1 + 2 + ... + n for all n from 1 to a certain
number nMax, entered by the user. Since we dont know ahead of time what nMax
will be, we cant just write
print('{0:3d}
print('{0:3d}
print('{0:3d}
print('{0:3d}
...
{1:6g}'.format(1,
{1:6g}'.format(2,
{1:6g}'.format(3,
{1:6g}'.format(4,
1))
3))
6))
10))
It would also make little sense, since we would have to compute all the sums by
hand. Even if we knew nMax, say nMax = 1000, and used a formula for the sum
69
n = 1
print('{0:3d} {1:6g}'.format(n, n*(n+1)/2))
n = n+1
print('{0:3d} {1:6g}'.format(n, n*(n+1)/2))
n = n+1
print('{0:3d} {1:6g}'.format(n, n*(n+1)/2))
n = n+1
...
<condition> is an expression that can use relational operators <, >, <=, >=, == (is
equal), and != (is not equal). Its value is either True or False. Try it:
>>> 6 <= 6
True
>>> 5 <= 6
True
>>> 5 <= 4
False
<condition> can also include logical operators: and, or, not. For example:
>>> x = 4
>>> x > 0 and x <= 3
False
>>> not x < 0
True
As long as the condition remains true, the program repeats the statements in the
while block (the statements that are indented under while). Such repetitions are
called iterations. Usually the condition includes a test for a variable that is updated
on each iteration, so eventually the condition becomes false and the iterations stop.
The program then continues with the first statement after the while block.
70
Example 1
nMax = 10
n = 1
while n <= nMax:
print('{0:3d} {1:6g}'.format(n, n*(n+1)/2))
n += 1
1
2
3
4
5
6
7
8
9
10
1
3
6
10
15
21
28
36
45
55
Thanks to iterations, the program code has the same length regardless of whether we
run it with nMax = 10 or nMax = 10000.
Example 2
Suppose we dont know the formula for the sum and want to use a brute force
approach. We can calculate the sum 1 + 2 + ... + n using a loop:
sum1n = 0
i = 1
while i <= n:
sum1n += i
i += 1
71
nMax = 10
n = 1
while n <= nMax:
sum1n = 0
i = 1
while i <= n:
sum1n += i
i += 1
print('{0:3d} {1:6d}'.format(n, sum1n))
n += 1
Reminder: avoid using the names of built-in functions (such as sum, min,
max, int, str, bytes, len, pow, list, and file) for your variables.
Our programs are getting bigger, and it is no longer practical to test them in an
interactive environment. It is much better to create a program with a text editor of
some kind (for example, Notepad) and save it in a file. You can even use a word
processor such as MS Word just make sure you save the file as text only. Or
you can use an IDE (Integrated Development Environment).
It is customary to give Python source files (that is, files that hold the
texts of Python programs) the extension .py.
IDLE, included with the Python release, provides a simple editor that allows you to
enter and edit a program, save it in a file and conveniently run it. Lets try it. In
IDLE, press Ctrl-N to open a new editor window (or use the menu command
File/New Window). Type in the little program above and save it in a source file
Sums1toN.py (Press Ctrl-S or use the menu command File/Save). Put the file
in a folder of your choice, for example C:\mywork. Press F5 to interpret and run the
program. If you make changes to your program and press F5 again, IDLE will
prompt you to save the changed file.
You can have several editor windows open, and you can cut and paste text from one
to another.
See www.skylit.com/python/Appendix-A.html for details and for instructions
on how to run Python programs in other ways.
72
Your program works, but it is inefficient: it keeps recalculating sums from scratch,
over and over. If we have found 1 + 2 + ... + 49 , we only need to add 50 to it to get
1 + 2 + ... + 50 .
Example 3
We can keep track of the sum and eliminate the nested while loop, like this:
nMax = 10
n = 1
sum1n = 0
while n <= nMax:
sum1n += n
print('{0:3d} {1:6d}'.format(n, sum1n))
n += 1
You might say: Who cares? Computers are fast anyway. However, such
inefficiencies can visibly slow down even the fastest computer if the task is large
enough. Here the version with nested loops will perform a number of operations
proportional to nMax2, while in the streamlined version, with one loop, the number of
operations will be proportional to nMax a big difference. In this case, the more
efficient version also has shorter code.
We are almost done with our project. The only remaining question is: How do we
get nMax from the user?
Python has a built-in function input, which lets you issue a prompt and read a string
from the standard input stream stdin, that is, the keyboard.
Example 4
>>> word = input('Enter any word: ')
Enter any word: Hello
>>> word
'Hello'
input returns a string. We can convert it into an int by applying the built-in
function int.
73
Example 5
>>> s = input('Enter a positive integer: ')
Enter a positive integer: 10
>>> nMax = int(s)
>>> nMax
10
This works, as long as the user enters a string that represents a valid integer. But
what if the user mistypes? For example:
The program is aborted with a cryptic error message. In the technical Python lingo,
the program raises an exception in this case, a ValueError exception. This is
not very friendly! We should really give the user another chance. Luckily, Python
lets us convert the entered string into an int tentatively and catch the exception if
it occurs.
Example 6
try:
nMax = int(s)
except ValueError:
print('Invalid input')
We will put this code inside a while loop to give the user as many tries as he wants:
nMax = -1
while nMax <= 0:
s = input('Enter a positive integer: ')
try:
nMax = int(s)
except ValueError:
print('Invalid input')
We have initially set nMax to -1, so that the while loop executes the first time.
Look at the complete text of this program it is in the Sums1toN.py file in the
PY\Ch04 folder on the Student Disk.
74
inefficient to use this call within a loop (the same problem as with nested loops). It
would also have spoiled all our fun!
Exercises
1.
2.
Write a program that prompts the user for a positive integer n and prints all
positive multiples of 6 (6, 12, 18, etc.) that do not exceed n.
3.
4.
k =1
k =1
3s2 (n)
for
s1 (n)
from the
k =1
resulting table.
5.
Use only one while loop. (Actually, in Python, you can write this function
without any loops, on one line. Can you figure out how?) 3
75
6.
Write a function myPow(x, n) that returns x n , where x > 0 and n is a nonnegative integer. Do not use the ** operator or the math.pow function
use one while loop. Hint: x 0 = 1 . 3
7.
8.
The smallest perfect number is 6. Write a program that finds and prints out
the next perfect number.
9.
1. Dont forget from math import sqrt. After that you can call
sqrt(x) it returns x .
2. The statement
print('{0:3d} {1:8.6f} {2:8.6f}'.format(n, sum, p))
76
4.6 Review
Terms and notation introduced in this chapter:
Sequence
Term (of a sequence)
Converging sequence
Limit of a sequence
Arithmetic sequence
Geometric sequence
Sigma notation
Series
Partial sum
Converging series
Diverging series
Augmented assignment
operators
a
k =1
a
k =1