Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
70 views22 pages

Litvin Python Chapter 04

litvin python Chapter 04 litvin python Chapter 04 litvin python Chapter 04

Uploaded by

Omar Atreides
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views22 pages

Litvin Python Chapter 04

litvin python Chapter 04 litvin python Chapter 04 litvin python Chapter 04

Uploaded by

Omar Atreides
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Mathematics

for the Digital Age


and

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]

Copyright 2010 by Maria Litvin, Gary Litvin, and


Skylight Publishing
All rights reserved. No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without
the prior written permission of the authors and Skylight Publishing.

Library of Congress Control Number: 2009913596


ISBN 978-0-9824775-8-8
The names of commercially available software and products mentioned in this book are
used for identification purposes only and may be trademarks or registered trademarks
owned by corporations and other commercial entities. Skylight Publishing and the authors
have no affiliation with and disclaim any sponsorship or endorsement by any of these
products manufacturers or trademarks owners.

1 2 3 4 5 6 7 8 9 10

15 14 13 12 11 10

Printed in the United States of America

4 Sequences, Sums, Iterations


4.1 Prologue
In math, a sequence is an infinite list of values. An element of a sequence is often
called a term. We will deal only with numeric sequences their terms are real
numbers. The terms of a sequence are numbered by integers, starting from 1 or
sometimes from 0:

a1 , a2 , ..., an , ...
or

b0 , b1 , ..., bn , ...

Copyright 2008-2010 by Skylight Publishing

The simplest sequence is the sequence of positive integers themselves: 1, 2, 3, 4, ....


Another simple sequence is the sequence of positive odd integers: 1, 3, 5, 7, ....
Sometimes it is not obvious how a sequence is defined, given only its first few terms.
For example: 1, 2, 5, 12, 27, .... It turns out we used the formula an = 2n n to
calculate the n-th term. So, it often helps to include the formula for the n-th term in
the description of the sequence. For example: 1, 2, 5, ..., 2n n, ... . Or we can say

simply: Consider a sequence {an = 2n n} . The n-th term formula is called the

general term of the sequence.


You can view a sequence of real numbers as a function whose domain is all positive
integers (or all non-negative integers) and whose outputs are real numbers: f (i ) = ai .
Like any other function, we can describe a sequence in words or with a formula.
Sometimes, the only way to generate a long enough segment of a sequence is by
using a computer. For example, the sequence of all prime numbers: 2, 3, 5, 7, 11... .
(An integer is called a prime if it is greater than 1 and is evenly divisible only by 1
and by itself.) In this sequence, we can find each term by looking for the smallest
number not evenly divisible by any of the preceding terms. Another example: the
sequence of all digits of : 3, 1, 4, ... .

57

58

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

is a database of sequences of integers on


There
www.research.att.com/~njas/sequences/Seis.html.

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.

Copyright 2008-2010 by Skylight Publishing

4.2 Arithmetic and Geometric Sequences


There are two types of sequences that come up frequently in mathematical problems:
the arithmetic sequence and the geometric sequence.
In an arithmetic sequence, the difference between any two consecutive
terms is the same.

In other words, in an arithmetic sequence, an = an 1 + d , where d is some constant.


d is called the common difference. Thus an arithmetic sequence has the form
c, c + d , c + 2d , ..., c + (n 1)d , ... . The general term of an arithmetic sequence can
be written as an = c + (n 1)d . The simplest arithmetic sequence is, again, the
sequence of all positive integers.

Example 1
1, 3, 5, ..., 2n 1, ... ( d = 2 ) and 5, 15, 25, ..., 5 + 10(n 1), ... ( d = 10 ) are both
arithmetic sequences.

4.2 ~ ARITHMETIC AND GEOMETRIC SEQUENCES

59

In a geometric sequence the ratio of the next term to the previous is


constant.
In other words, in a geometric sequence, an = an 1 r , so it has the form

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

Copyright 2008-2010 by Skylight Publishing

1, 2, 4, 8, 16, ... and

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

Figure 4-1. Arithmetic and geometric mean

Exercises
1.

Come up with your own interesting sequence, defined in words. State its
n-th term.

Copyright 2008-2010 by Skylight Publishing

60

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

2.

Determine a formula for the general term of the sequence


1 1 1 1 1 1
, , ,
, ,
, ... . 3
2 6 12 20 30 42

3.

Show that if a0 , a1 , a2 , ... is an arithmetic sequence, then a0 , a3 , a6 , a9 , ... is


also an arithmetic sequence.

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.

What is the limit of the sequence 0,

11.

n 2

Does the sequence an =


converge? If so, what is the limit?
n 5

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,

13 + 23 + 33 + ... + n3 = (1 + 2 + 3 + ... + n ) . So it turns out that the sum of the first n


cubes is always a perfect square.
2

Copyright 2008-2010 by Skylight Publishing

There is special sigma notation for sums: a1 + a2 + ... + an is often written as

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

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

If we multiply both sides by 2, we get:

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

for n 1 , that is sn 1 = 2n 1 1 . Then


sn = sn 1 + 2n 1 = ( 2n 1 1) + 2n 1 = 2 2n 1 1 = 2n 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.

Copyright 2008-2010 by Skylight Publishing

Exercises
1.

In Chapter 1, we showed that the sum 1 + 2 + ... + n is equal to

n(n + 1)
,
2

1+ n
, times the number of
2
terms n. Show that the same is true for any arithmetic sequence.

which is the average of the first and last terms,

2.

Derive the formula for the sum of the first n terms of the arithmetic sequence
n

[a
i =1

+ (i 1)d ] in a different way, by reducing it to the known sum

1 + 2 + ... + ( n 1) . After simplification, your result should be the same as in


n

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.4 ~ INFINITE SUMS

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.

Derive a formula for sn = c + cr + cr 2 + ... + cr n 1 . Verify the result by


applying it to the geometric sequence from Question 4. Hint: recall what
we did with 1 + 2 + 4 + ... + 2n and use a similar method.

6.

Find

d 10

. 3

d =1

(2
n

7.

Find

k =1

Copyright 2008-2010 by Skylight Publishing

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.

4.4 Infinite Sums


An infinite sum? Can a1 + a2 + a3 + ... + an + ... make any sense? Isnt such a sum
always infinite? When you encounter infinity, it always raises infinitely many
questions.
As it turns out, there is a way to give a precise mathematical meaning to an
expression a1 + a2 + a3 + ... + an + ... . Such an expression is called a series. The way
to approach it is this: consider a sequence of sums s1 , s2 , ..., sn , ... , where
s1 = a1
s2 = a1 + a2
...
sn = a1 + ... + an
...

64

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

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.

Copyright 2008-2010 by Skylight Publishing

For the geometric series

A series is often written in sigma notation, as follows:

a
i =1

symbol used for infinity. So

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.

4.4 ~ INFINITE SUMS

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


Copyright 2008-2010 by Skylight Publishing

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

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

1 1 1
6 5 4

1
3

1
2

Figure 4-2. A tower of bricks with one support can extend


to the right as far as we want

Example 3

Copyright 2008-2010 by Skylight Publishing

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.

Find the sum of the telescopic series

2.

Does the series

n =1

sum? 3

n +1

100n

converge? Explain. If yes, then what is its

67

4.4 ~ INFINITE SUMS

3.

If {d 0 , d1 , d 2 ,...} is the sequence of digits of , {3, 1, 4, ...}, does

dn

10
n=0

converge? If yes, what is the sum?


4.

For which values of r does the geometric series 1 + r + r 2 + ... converge? 3

5.

1 1
1
Does the series 1 + + + ... +
+ ... converge? Explain your reasoning.
3 5
2n 1

6.

Does the series

n =1

Copyright 2008-2010 by Skylight Publishing

7.

converge? Explain your reasoning.

The figure below illustrates the process or making a snowflake:

At each step, each straight line segment on the snowflakes perimeter is


. If we keep repeating this process infinitely, we get a
replaced by
curve known as the Koch Snowflake. Suppose the perimeter of the first
P2 3
triangle is P and its area is A (where A =
). Determine the perimeter
36
and the area of the Koch snowflake after n iterations. Is the perimeter of the
Koch Snowflake finite? What about the area?

68

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

4.5 Iterations in Python


In this section we will create a Python program that prompts the user to enter a
positive integer nMax and prints out the sums 1 + 2 + ... + n for n from 1 to nMax. But
first let us review what we have learned so far about Pythons arithmetic operators.

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.

Copyright 2008-2010 by Skylight Publishing

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

4.5 ~ ITERATIONS IN PYTHON

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

our program would be too long.


Fortunately, Python provides an iterative statement, called a while loop, which allows
us to repeat the same block of statements multiple times (but with different values of
variables) while a certain condition holds true. The syntax for the while loop is:
while <condition>:
...
...

Copyright 2008-2010 by Skylight Publishing

<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

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

Example 1
nMax = 10
n = 1
while n <= nMax:
print('{0:3d} {1:6g}'.format(n, n*(n+1)/2))
n += 1

The output is:

Copyright 2008-2010 by Skylight Publishing

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

# same as sum1n = sum1n + i

This loop can be nested within the first loop:

4.5 ~ ITERATIONS IN PYTHON

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.

Copyright 2008-2010 by Skylight Publishing

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

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

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:

Copyright 2008-2010 by Skylight Publishing

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.

4.5 ~ ITERATIONS IN PYTHON

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:

Copyright 2008-2010 by Skylight Publishing

>>> s = input('Enter a positive integer: ')


Enter a positive integer: 1.0
>>> nMax = int(s)
...
ValueError: invalid literal for int() with base 10: '1.0'

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

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

mentioned earlier that Python has a built-in function sum. To calculate


We
1 + 2 + ... + n we could simply write sum(range(1, n+1)). But it would be

inefficient to use this call within a loop (the same problem as with nested loops). It
would also have spoiled all our fun!

Copyright 2008-2010 by Skylight Publishing

Exercises
1.

Modify the Sums1toN.py program to accept only an odd positive integer


nMax from the user and print the sums of positive odd integers 1 + 3 + ... + n
for n = 1, 3, ..., nMax.

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.

Using Sums1toN.py as a prototype, write a program that prompts the user


to enter a positive integer nMax and displays n and n! (n-factorial) for n from
1 to nMax. n! = 1 2 ... n . 3

4.

k =1

k =1

Write a program that prints n, s1 (n) = k , s2 (n) = k 2 , and

3s2 (n)
for
s1 (n)

n = 1, 2, 3, ..., 20. Try to guess the general formula for

from the

k =1

resulting table.
5.

Write a function printSquare(n) that displays a square whose side has


n stars. For example, for n = 5, the output should be:
*****
*
*
*
*
*
*
*****

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

4.5 ~ ITERATIONS IN PYTHON

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.

Write a function smallestDivisor that takes an integer n > 1 and returns


its smallest divisor that is greater than 1. For example:
smallestDivisor(15) should return 3; smallestDivisor(7) should
return 7. Hint: d is not a divisor of n if and only if n % d != 0.

8.

A positive integer is called a perfect number if it is equal to the sum of all of


its divisors, including 1 but excluding the number itself. For example, 6 = 1
+ 2 + 3. Write a function sumOfDivisors that takes a positive integer n
and returns the sum of all its divisors (excluding n). Hint:
if n % d == 0:
sumDivs += d

Copyright 2008-2010 by Skylight Publishing

The smallest perfect number is 6. Write a program that finds and prints out
the next perfect number.
9.

Using Sums1toN.py as a prototype, write a program that prompts the user


to enter a positive integer nMax and displays the partial sums of the series
1 1 1
1
1 + + + + ... + 2 + ... for n from 1 to nMax. For each n, display n, the
4 9 16
n
corresponding sum, and 6 sum . Test your program with a wide range of
user input including a non-number, a negative integer, and a valid positive
integer.
Hints:

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

will print all three numbers in an appropriate format.

76

CHAPTER 4 ~ SEQUENCES, SUMS, ITERATIONS

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

Some of the Python features introduced in this chapter:


from math import sqrt

Copyright 2008-2010 by Skylight Publishing

+=, -=, *=, etc.


while <some condition is true>:
...
...
s = input('Enter ... ')
try:
n = int(s)
except ValueError:
print('Invalid input...')
print('n={0:3d} x={1:7.2g}'.format(n, x))

a
k =1

a
k =1

You might also like