Chapter 02: Basic Structures: Sets, Functions, Sequences, Sums and Matrices

Example 01: Page 156

In [3]:
#To generate a sequence a_n=1/n
i=1.0 #floating point division
n=input("enter the number of terms in the sequence");
print "a_n=1/n"
print "when n=",n,"a_n is"
for i in range(1,n+1): #iteration till the number of terms specified by the user
    a=1.0/i
    print "1/",i,",",
print "\n"
for i in range(1,n+1): #iteration till the number of terms specified by the user
    a=1.0/i
    print a,",",
enter the number of terms in the sequence5
a_n=1/n
when n= 5 a_n is
1/ 1 , 1/ 2 , 1/ 3 , 1/ 4 , 1/ 5 , 

1.0 , 0.5 , 0.333333333333 , 0.25 , 0.2 ,

Example 02: Page 157

In [5]:
n=input("Enter the number of terms in the sequence to generate the geometric progression");
i=1
print"the list of terms",
for i in range (n+1):print"b",i,",",
print "begins with", 
for i in range (n+1): #iterate for the number of terms given as input
    b_n=(-1)**i
    print b_n,
print"\n","the list of terms",
for i in range (n+1):print"c",i,",",
print "begins with",   
for i in range (n+1): #iterate for the number of terms given as input
    c_n=2*(5**i)
    print c_n,
print"\n","the list of terms",
for i in range (n+1):print"c",i,",",
print "begins with",
for i in range (n+1): #iterate for the number of terms given as input
    d_n=6.0*((1.0/3.0)**i)
    print d_n, #prints the fraction values in decimals.  Floating point division

    
   
    
Enter the number of terms in the sequence to generate the geometric progression5
the list of terms b 0 , b 1 , b 2 , b 3 , b 4 , b 5 , begins with 1 -1 1 -1 1 -1 
the list of terms c 0 , c 1 , c 2 , c 3 , c 4 , c 5 , begins with 2 10 50 250 1250 6250 
the list of terms c 0 , c 1 , c 2 , c 3 , c 4 , c 5 , begins with 6.0 2.0 0.666666666667 0.222222222222 0.0740740740741 0.0246913580247

Example 03: Page 157

In [6]:
n=input("Enter the number terms in the sequence");
s_n=-1+4*n
t_n=7-3*n
i=0
print "The list of terms",
for i in range(n):  
    print "s",i,",",
print "begins with",
for i in range(n):#generates the sequence for -1*4i
    print -1+4*i,
print "\nThe list of terms",
for i in range(n):
    print "t",i,",",
print "begins with",
for i in range(n):#generates the sequence for 7-3i
    print 7-3*i,
    
Enter the number terms in the sequence5
The list of terms s 0 , s 1 , s 2 , s 3 , s 4 , begins with -1 3 7 11 15 
The list of terms t 0 , t 1 , t 2 , t 3 , t 4 , begins with 7 4 1 -2 -5

Example 05: Page 158

In [9]:
a=[2,0,0,0] #assigning a[0]=2 (Given)

for i in range(1,4):#iteration to run till a[3]
    a[i]=a[i-1]+3
    print "a[",i,"]",a[i]
a[ 1 ] 5
a[ 2 ] 8
a[ 3 ] 11

Example 06: Page 158

In [11]:
a=[3,5,0,0] #assingning a[0],a[1] to the given values

for i in range(2,4): # iterations to find the successive values. If values are to be found for further terms the for loop "stop" has to be modified
    a[i]=a[i-1]-a[i-2]
    print "a[",i,"]",a[i]
a[ 2 ] 2
a[ 3 ] -3

Example 07: Page 158

In [1]:
f=[0,1,0,0,0,0,0] #assingning a[0],a[1] to the given values
print "Fibonacci series is"
for i in range(2,7): # iterations to find the successive values. If values are to be found for further terms the for loop "stop" has to be modified
    f[i]=f[i-1]+f[i-2]
    print "f[",i,"]=f[",i-1,"]+f[",i-2,"]=",f[i]
Fibonacci series is
f[ 2 ]=f[ 1 ]+f[ 0 ]= 1
f[ 3 ]=f[ 2 ]+f[ 1 ]= 2
f[ 4 ]=f[ 3 ]+f[ 2 ]= 3
f[ 5 ]=f[ 4 ]+f[ 3 ]= 5
f[ 6 ]=f[ 5 ]+f[ 4 ]= 8

Example 08: Page 159

In [3]:
n=1
result=0
number=input("Enter the number");
for i in range(1,number):
    n=n+i*n 
print "The factorial of",number,"is",n
Enter the number5
The factorial of 5 is 120

Example 18: Page 164

In [2]:
#finding the summation of j^2
up=input("Enter the upper limit for the operation j^2");
low=input("Enter the lower limit for the operation j^2");
sum=0
print "The square of terms form 1 to n",
for j in range (low,up+1): #summation.  Iteration from lower to upper limit.
    print j,"^2+",
    j=j**2 #square function is computed as '**'
    sum=sum+j
print "=",sum
                
Enter the upper limit for the operation j^25
Enter the lower limit for the operation j^21
The square of terms form 1 to n 1 ^2+ 2 ^2+ 3 ^2+ 4 ^2+ 5 ^2+ = 55

Example 19: Page 164

In [1]:
k=4 #lower limit
sum=0
print "The value for the sequence",
for k in range (4,8+1,1): #8+1 , 8 is the upper limit, in python to make for loop run till the limit equal to upper limit we give a +1.
    print "(-1)^",k,"+",
    sum=sum+((-1)**k)
print "=",sum
The value for the sequence (-1)^ 4 + (-1)^ 5 + (-1)^ 6 + (-1)^ 7 + (-1)^ 8 + = 1

Example 21: Page 165

In [3]:
globals()['j']=0
i=0
globals()['s']=0
upj=input("Enter the upper limit for the inner summation");
lowj=input("Enter the lower limit for the inner summation");
upi=input("Enter the upper limit for the outer summation");
lowi=input("Enter the lower limit for the outer summation");
for i in range (lowj,upj+1):
    j=j+i
for l in range(lowi,upi+1):
    s=s+(j*l)
print s
    
    
Enter the upper limit for the inner summation3
Enter the lower limit for the inner summation1
Enter the upper limit for the outer summation4
Enter the lower limit for the outer summation1
60

Example 13: Page 161

In [4]:
#To print series 1 once, 2 twice, 3 thrice and so on
a=[]
i=1
for i in range(1,10+1): #for loop to initialise the number
    for j in range(1,i+1):#for loop to iterate to make the count
        print i,
    
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10

Example 22: Page 166

In [5]:
s=0 #initialise it to zero to store the results
globals()['res']=0 #difining result as global variable since it has to be accessed outside the loop
print "Sum of values of s for all the members of the set {",
for s in range (0,4+1,2): #iterate for terms 0,4,6
    print s,
    res=res+s
print "} is",res
Sum of values of s for all the members of the set { 0 2 4 } is 6

Example 02: Page 178

In [6]:
def getmat(): #function to get the matrix elements
    m = int(input('number of rows, m = '))
    n = int(input('number of columns, n = '))
    matrix = []; columns = []

    for i in range(0,m):
        matrix.append([])
        for j in range(0,n):
            matrix[i].append(0)
            print ('entry in row: ',i+1,' column: ',j+1)
            matrix[i][j] = int(input())
    return (matrix)

def matrixADD(m1,m2): #function to add the matrix.
    z=[]
    for i in range (len(m1)):
        tem = []
        for j in range (len(m2)):
            x=m1[i][j]+m2[i][j]
            tem.append(x)
        z.append(tem)
    return z    
        


mat1=[]
mat2=[]
Z=[]
print "Enter the elements of matrix 1"
mat1=getmat() #function call
print "Enter the elements of matrix 2"
mat2=getmat() #function call
print "Addition of \n matrix 1",mat1,"and \n matrix 2",mat2,"is \n",matrixADD(mat1,mat2) #function call to add 
Enter the elements of matrix 1
number of rows, m = 3
number of columns, n = 3
('entry in row: ', 1, ' column: ', 1)
1
('entry in row: ', 1, ' column: ', 2)
0
('entry in row: ', 1, ' column: ', 3)
-1
('entry in row: ', 2, ' column: ', 1)
2
('entry in row: ', 2, ' column: ', 2)
2
('entry in row: ', 2, ' column: ', 3)
-3
('entry in row: ', 3, ' column: ', 1)
3
('entry in row: ', 3, ' column: ', 2)
4
('entry in row: ', 3, ' column: ', 3)
0
Enter the elements of matrix 2
number of rows, m = 3
number of columns, n = 3
('entry in row: ', 1, ' column: ', 1)
3
('entry in row: ', 1, ' column: ', 2)
4
('entry in row: ', 1, ' column: ', 3)
-1
('entry in row: ', 2, ' column: ', 1)
1
('entry in row: ', 2, ' column: ', 2)
-3
('entry in row: ', 2, ' column: ', 3)
0
('entry in row: ', 3, ' column: ', 1)
-1
('entry in row: ', 3, ' column: ', 2)
1
('entry in row: ', 3, ' column: ', 3)
2
Addition of 
 matrix 1 [[1, 0, -1], [2, 2, -3], [3, 4, 0]] and 
 matrix 2 [[3, 4, -1], [1, -3, 0], [-1, 1, 2]] is 
[[4, 4, -2], [3, -1, -3], [2, 5, 2]]

Example 03: Page 179

In [7]:
# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[1,0,4],
    [2,1,1],
    [3,1,0],
     [0,2,2]]
# 3x4 matrix
Y = [[2,4],
    [1,1],
    [3,0]]
# result is 3x4
result = [[0,0],
         [0,0],
         [0,0,],
          [0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]
print "The multiplication of the two matrices AB is"

for r in result:
   print(r)
The multiplication of the two matrices AB is
[14, 4]
[8, 9]
[7, 13]
[8, 2]

Example 05: Page 181

In [8]:
# Program to transpose a matrix using nested loop
# iterate through rows
def mattrans(X,result):
    print "The transpose is"
    for i in range(len(X)):
   # iterate through columns
       for j in range(len(X[0])):
           result[j][i] = X[i][j]
    for r in result:
        print(r)
        
def getmat():
    row = int(input('number of rows = '))
    col = int(input('number of columns = '))
    matrix = []; columns = []

    for i in range(0,row):
        matrix.append([])
        for j in range(0,col):
            matrix[i].append(0)
            print ('entry in row: ',i+1,' column: ',j+1)
            matrix[i][j] = int(input())
    for c in range(col):
        for r in range(row):
            result[c][r]=0
    mattrans(matrix,result)
    


print "Enter the elements of the matrix"
getmat()
#mattrans(mat1)
Enter the elements of the matrix
number of rows = 2
number of columns = 3
('entry in row: ', 1, ' column: ', 1)
1
('entry in row: ', 1, ' column: ', 2)
2
('entry in row: ', 1, ' column: ', 3)
3
('entry in row: ', 2, ' column: ', 1)
4
('entry in row: ', 2, ' column: ', 2)
5
('entry in row: ', 2, ' column: ', 3)
6
The transpose is
[1, 4]
[2, 5]
[3, 6]
[8, 2]