Chapter 4: Iteration

Example 4.1, page no. 60

In [1]:
i=1
print "Enter a positive integer: "
n = int(raw_input())
s=0
while (i <= n):
    s += i
    i += 1
print "The sum of the first %d integers is %d" %(i,s)
Enter a positive integer: 
5
The sum of the first 6 integers is 15

Example 4.2, page no. 61

In [2]:
print "Enter a positive integer: "
bound = int(raw_input())
s=0.0
i=0
while (s < bound):
    i += 1
    s += 1.0/i

print "The sum of the first %d reciprocals is %f" %(i,s)
Enter a positive integer: 
5
The sum of the first 83 reciprocals is 5.002068

Example 4.3, page no. 61

In [3]:
import math
print "Enter a positive number: "
x = float(raw_input())
while (x > 0):
    print "sqrt(%d) = %f "%(x,math.sqrt(x))
    print "Enter another positive number (or 0 to quit): "
    x = float(raw_input())
Enter a positive number: 
5
sqrt(5) = 2.236068 
Enter another positive number (or 0 to quit): 
3
sqrt(3) = 1.732051 
Enter another positive number (or 0 to quit): 
0

Example 4.4, page no. 62

In [5]:
i=1
print "Enter a positive integer: ";
n = int(raw_input())
s=0
while(True):
    if (i > n):
        break # terminates the loop immediately
    s += i
    i += 1
print "The sum of the first %d integers is %d" %(n,s)
Enter a positive integer: 
5
The sum of the first 5 integers is 15

Example 4.5, page no. 62

In [6]:
print "Enter a positive integer: "
bound = int(raw_input())
print "Fibonacci numbers < %d:\n0, 1"  % bound ,
f0=0
f1=1
while (True):
    f2 = f0 + f1
    if (f2 > bound):
        break
    print ", %d" % f2,
    f0 = f1
    f1 = f2
                                                                                                                  
Enter a positive integer: 
10
Fibonacci numbers < 10:
0, 1 , 1 , 2 , 3 , 5 , 8

Example 4.6, page no. 63

In [6]:
import sys
print "Enter a positive integer: "
bound = int(raw_input())
print "Fibonacci numbers < %d:\n0, 1"  % bound ,
f0=0
f1=1
while (True):
    f2 = f0 + f1
    if (f2 > bound):
        sys.exit(0)
    print ", %d" % f2,
    f0 = f1
    f1 = f2
                           
Enter a positive integer: 
10
An exception has occurred, use %tb to see the full traceback.

SystemExit: 0
Fibonacci numbers < 10:
0, 1 , 1 , 2 , 3 , 5 , 8
To exit: use 'exit', 'quit', or Ctrl-D.

Example 4.7, page no. 63

In [1]:
print "Enter a positive integer: "
bound = int(raw_input())
print "Fibonacci numbers < %d:\n0, 1"  % bound ,
f0=0
f1=1
# Error : infinite loop !
while (True):
    f2 = f0 + f1
    # By commenting the below if statement, it goes to infinite.
    if (f2 > bound):
        break
    print ", %d" % f2,
    f0 = f1
    f1 = f2
Enter a positive integer: 
Fibonacci numbers < 10:
0, 1 , 1 , 2 , 3 , 5 , 8

Example 4.8, page no. 64

In [3]:
i=0
print "Enter a positive integer: "
n = int(raw_input())
s=0
while i<=n:
    s += i
    i += 1
print "The sum of the first %d integers is %d" %(n,s)
Enter a positive integer: 
10
The sum of the first 10 integers is 55

Example 4.9, page no. 65

In [4]:
print "Enter a positive integer: "
bound = int(raw_input())
print "Factorial numbers < %d:\n1, 1" %bound,
f=1
i=1
while f < bound:
    i += 1
    f *= i
    print ", %d" %f,
Enter a positive integer: 
10
Factorial numbers < 10:
1, 1 , 2 , 6 , 24

Example 4.10, page no. 66

In [5]:
print "Enter a positive integer: "
n = int(raw_input())
s=0;
for i in range(0,n+1):
    s += i
print "The sum of the first %d integers is %d" %(n,s)
Enter a positive integer: 
10
The sum of the first 10 integers is 55

Example 4.11, page no. 66

In [6]:
print "Enter a positive integer: "
n = int(raw_input())
s=0
for i in range(1,n/2): # the scope of this i is this loop
    s += i

for i in range(n/2,n+1): # the scope of this i is this loop
    s += i
print "The sum of the first %d integers is %d" % (n,s)
Enter a positive integer: 
10
The sum of the first 10 integers is 55

Example 4.12, page no. 66

In [7]:
print "Enter a positive integer: "
bound = int(raw_input())

print "Factorial numbers that are <= %d:\n1, 1" %bound,
f=1
for i in range(2,bound+1):
    f *= i
    print ", %d" % f,
Enter a positive integer: 
10
Factorial numbers that are <= 10:
1, 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 , 3628800

Example 4.13, page no. 67

In [8]:
for i in range(10,0,-1):
    print  i,
10 9 8 7 6 5 4 3 2 1

Example 4.14, page no. 67

In [9]:
prime = True
print "Enter a positive integer: "
n = int(raw_input())
if (n < 2):
    print "%d is not prime." %n
    prime = False
elif (n < 4):
    print "%d is prime." %n
    prime = False
elif (n%2 == 0):
    print "%d = 2* %d" %(n,n/2)
    prime = False
else:
    for d in range(3,n/2+1):
        if (n%d == 0):
            print "%d = %d * %d" %(n,d,n/d)
            prime = False
if prime:            
    print "%d is prime."%n
Enter a positive integer: 
11
11 is prime.

Example 4.15, page no. 68

In [10]:
print "Enter positive integers (0 to quit): ";
n = int(raw_input())
m = n
while n > 0:
    n = int(raw_input())
    if n > m :
        m = n

print "max = %d" % m
Enter positive integers (0 to quit): 
5
19
42
1
0
max = 42

Example 4.16, page no. 68

In [11]:
print "Enter positive integers (0 to quit): ";
n = int(raw_input())
m = n
while n > 0:    
    if n < m :
        m = n
    n = int(raw_input())

print "min = %d" % m
Enter positive integers (0 to quit): 
5
19
42
1
0
min = 1

Example 4.17, page no. 69

In [12]:
m = 95
n = 11
while m%n > 0:
    print "%d modulo %d = %d" %(m,n,m%n)
    m -= 3
    n += 1
95 modulo 11 = 7
92 modulo 12 = 8
89 modulo 13 = 11
86 modulo 14 = 2
83 modulo 15 = 8

Example 4.18, page no. 69

In [13]:
for x in range(1,13):
    for y in range(1,13):
        print "%4d" % (x*y),
    print ""
   1    2    3    4    5    6    7    8    9   10   11   12 
   2    4    6    8   10   12   14   16   18   20   22   24 
   3    6    9   12   15   18   21   24   27   30   33   36 
   4    8   12   16   20   24   28   32   36   40   44   48 
   5   10   15   20   25   30   35   40   45   50   55   60 
   6   12   18   24   30   36   42   48   54   60   66   72 
   7   14   21   28   35   42   49   56   63   70   77   84 
   8   16   24   32   40   48   56   64   72   80   88   96 
   9   18   27   36   45   54   63   72   81   90   99  108 
  10   20   30   40   50   60   70   80   90  100  110  120 
  11   22   33   44   55   66   77   88   99  110  121  132 
  12   24   36   48   60   72   84   96  108  120  132  144 

Example 4.19, page no. 70

In [14]:
import math
# defines pow() and log()

print "Enter a positive integer: "
n = int(raw_input())
d=0 # the discrete binary logarithm of n
p2d=1  # = 2^d
i = n
while i > 1:
    # INVARIANT: 2^d <= n/i < 2*2^d
    p2d=math.pow(2,d) # = 2^d
    print "%2d  <= %2d" %(p2d,2*p2d)
    i /= 2
    d += 1

p2d=math.pow(2,d) # = 2^d
print "%2d  <= %2d < %2d" %(p2d,n,2*p2d)
print " The discrete binary logarithm of is %d" % d 
lgn = math.log(n)/math.log(2) # base 2 logarithm
print "The continuous binary logarithm of is %f" % lgn
Enter a positive integer: 
17
 1  <=  2
 2  <=  4
 4  <=  8
 8  <= 16
16  <= 17 < 32
 The discrete binary logarithm of is 4
The continuous binary logarithm of is 4.087463

Example 4.20, page no. 71

In [15]:
i=1
print "Enter a positive integer: "
n = int(raw_input())
s=0
while (True):
    if (i > n):
        break
    s += i
    i += 1

print "The sum of the first %d integers is %d" %(i,s)
Enter a positive integer: 
10
The sum of the first 11 integers is 55

Example 4.21, page no. 71

In [16]:
count=0
s=0
print "Enter positive integers (0 to quit):" 
while True: # "forever"
    print "\t %d :" %(count + 1),
    n = int(raw_input())
    if (n <= 0):
        break
    count += 1
    s += n

print "The average of those %d positive numbers is " %count,
print float(s)/count
Enter positive integers (0 to quit):
	 1 :12
 	 2 :32
 	 3 :11
 	 4 :0
 The average of those 3 positive numbers is  18.3333333333

Example 4.22, page no. 72

In [17]:
for x in range(1,13):
    for y in range(1,13):
        if y>x:
            break
        else:
            print '%4d' %(x*y),
    print ''
   1 
   2    4 
   3    6    9 
   4    8   12   16 
   5   10   15   20   25 
   6   12   18   24   30   36 
   7   14   21   28   35   42   49 
   8   16   24   32   40   48   56   64 
   9   18   27   36   45   54   63   72   81 
  10   20   30   40   50   60   70   80   90  100 
  11   22   33   44   55   66   77   88   99  110  121 
  12   24   36   48   60   72   84   96  108  120  132  144 

Example 4.23, page no. 73

In [18]:
while True:
    n = int(raw_input('Enter int : '))
    if (n%2 == 0):
        continue
    if (n%3 == 0):
        break
    print "\tBottom of loop.\n"
print "\tOutside of loop.\n"
Enter int : 5
	Bottom of loop.

Enter int : 4
Enter int : 6
Enter int : 9
	Outside of loop.

Example 4.24, page no. 74

In [19]:
N=5
done=False
for i in range(N):
    for j in range(N):
        if done:
            break
        for k in range(N):
            if done:
                break
            if (i+j+k>N):
                done = True
            else:
                print i+j+k,
                print " ",
        print "* "
    print "." 
    done = False
0   1   2   3   4   * 
1   2   3   4   5   * 
2   3   4   5   * 
.
1   2   3   4   5   * 
2   3   4   5   * 
.
2   3   4   5   * 
.
3   4   5   * 
.
4   5   * 
.

Example 4.25, page no. 75

In [20]:
N=5
done=False
for i in range(N):
    for j in range(N):
        if done:
            break
        for k in range(N):
            if done:
                break
            if (i+j+k>N):
                done = True
            else:
                print i+j+k,
                print " ",
        print "* "
    print "." 
    done = False
0   1   2   3   4   * 
1   2   3   4   5   * 
2   3   4   5   * 
.
1   2   3   4   5   * 
2   3   4   5   * 
.
2   3   4   5   * 
.
3   4   5   * 
.
4   5   * 
.

Example 4.26, page no. 76

In [21]:
import random

# prints pseudo-random numbers:

for i in range(0,8):
    print random.random()

    
0.702115758628
0.969460447904
0.409934401112
0.700339443791
0.093528851602
0.132172955687
0.0162887279366
0.943010713478

Example 4.27, page no. 77

In [22]:
import random
# prints pseudo-random numbers:
print "Enter seed: "
seed = int(raw_input())
random.seed(seed);
for i in range(0,8):
    print random.random()
Enter seed: 
5
0.62290169489
0.741786989261
0.795193565566
0.942450283777
0.73989857474
0.922324996665
0.0290052282836
0.465622654378

Example 4.28, page no. 78

In [23]:
import random
for i in range(0,8):
    print random.random()
0.943356716998
0.648974553137
0.900900491751
0.113205964653
0.469069047782
0.24657283262
0.543760859236
0.573941187928

Example 4.29, page no. 79

In [24]:
import random
print "Enter minimum and maximum: "
m = int(raw_input())
n = int(raw_input())
# lowest and highest numbers
r = n - m + 1
# number of numbers in range
for i in range(0,20):
    j = int(random.random()*100 % r + m)
    print  j,
    print  " ",
Enter minimum and maximum: 
5
15
6   15   10   8   15   9   7   7   11   6   5   15   14   15   15   15   11   13   14   6