Chapter 7 : Array and Strings

Example 1, page no. 221

In [1]:
sum = 0
a1 = int(raw_input("Age:"))
sum += a1
a2 = int(raw_input("Age:"))
sum += a2
a3 = int(raw_input("Age:"))
sum += a3
a4 = int(raw_input("Age:"))
sum += a4
a5 = int(raw_input("Age:"))
sum += a5
print "The ages that were input are:"
print a1
print a2
print a3
print a4
print a5
print "Average = %d" %(sum/5)
Age:10
Age:20
Age:30
Age:40
Age:50
The ages that were input are:
10
20
30
40
50
Average = 30

Example 2, page no. 222

In [7]:
sum = 0.0
age = []
n = int(raw_input("Number of persons:"))
if n<=0 or n>5:
    print "Invalid number of person entered"
else:
    for i in range(n):
        age.append(int(raw_input("Age :")))
        sum += age[i]
    print "The ages input are:"
    for i in range (n):
        print age[i]
    print "The average is :",(sum/n)
Number of persons:5
Age :10
Age :20
Age :30
Age :40
Age :50
The ages input are:
10
20
30
40
50
The average is : 30.0

Example 7.1, page no. 225

In [18]:
a = []
n = int(raw_input("Size of vector ? "))
print "Vector elements ? "
for i in range (n):
    a.append(float(raw_input()))
large =  max(a)
small = min(a)
print "Largest element in vector is %8.2f" %large
print "Smallest element in vector is %8.2f" %small
Size of vector ? 7
Vector elements ? 
34.00
-9.00
12.00
10
-6.00
0.00
36.00
Largest element in vector is    36.00
Smallest element in vector is    -9.00

Example 7.2, page no. 226

In [17]:
a = []
n = int(raw_input("Size of vector ? "))
print "Vector elements ? "
for i in range (n):
    a.append(float(raw_input()))
for i in range (n-1):
    for j in range(i+1,n):
        if a[i]> a[j]:
            a[i],a[j]=a[j],a[i]
print "Vector elements in ascending order :"
for i in range(n):
    print "%8.2f" %a[i]
Size of vector ? 8
Vector elements ? 
91.00
20.00
1.00
7.00
34.00
11.00
-2.00
6.00
Vector elements in ascending order :
   -2.00
    1.00
    6.00
    7.00
   11.00
   20.00
   34.00
   91.00

Example 7.3, page no. 227

In [21]:
a = []
n = int(raw_input("Size of vector ? "))
print "Vector elements ? "
for i in range (n):
    a.append(float(raw_input()))
item = float(raw_input("Element to be inserted ?"))
pos = int(raw_input("Position of insertion ?"))
a.insert(pos-1, item)
print "Vector after insertion"
for ele in a:
    print ele,
Size of vector ? 7
Vector elements ? 
1.00
2.00
3.00
4.00
5.00
6.00
7.00
Element to be inserted ?10.00
Position of insertion ?1
Vector after insertion
10.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0

Example arrfunc.c, page no. 230

In [28]:
rollno = 4
subject = 3
def display(studentmarks):
    for r in range(rollno):
        print "\nRoll no.: ", r+1,
        for s in range(subject):
            print "%10.2f" %studentmarks[r][s],
marks =[[35.5, 40.5, 45.5],
        [50.5, 55.5, 60.5],
        [65.0, 70.0, 75.5],
        [80.0, 85.0, 90.0]]
display(marks)
Roll no.:  1      35.50      40.50      45.50 
Roll no.:  2      50.50      55.50      60.50 
Roll no.:  3      65.00      70.00      75.50 
Roll no.:  4      80.00      85.00      90.00

Example 7.4, page no. 240

In [46]:
import numpy

a = numpy.zeros((10, 10))
b = numpy.zeros((10, 10))
c = numpy.zeros((10, 10))

print "Input row & column of A matrix: "
n = int(raw_input("row: "))
m = int(raw_input("column: "))

print "Input row & column of B matrix: "
p = int(raw_input("row: "))
q = int(raw_input("column: "))

if n == p and m == q:
    print "Matrices can be added"
    print "Input A matrix: ",
    for i in range(n):
        for j in range(m):
            a[i][j] = int(raw_input())
        print ""
    print "Input B matrix: ",
    for i in range(p):
        for j in range(q):
            b[i][j] = int(raw_input())
        print ""
    for i in range(p):
        for j in range(q):
            c[i][j] = a[i][j] + b[i][j]
    print "Sum of A & B matrices: "
    for i in range(n):
        for j in range(m):
            print "%5d" %c[i][j],
        print ""
else:
    print "Matricess cannot be added"
Input row & column of A matrix: 
row: 3
column: 3
Input row & column of B matrix: 
row: 3
column: 3
Matrices can be added
Input A matrix: 1
2
3
 
4
5
6

7
8
9

Input B matrix: 1
2
3
 
4
5
6

7
8
9

Sum of A & B matrices: 
    2     4     6 
    8    10    12 
   14    16    18 

Example 7.5, page no. 233

In [48]:
import numpy

a = numpy.zeros((10, 10))
print "Enter the order of A matrix: ",
n = int(raw_input())
print "Input A matrix"
for i in range(n):
    for j in range(n):
        a[i][j] = int(raw_input())
trace = 0
for i in range(n):
    trace += a[i][i]
print "Trace = ", trace
Enter the order of A matrix: 3
 Input A matrix
1
2
3
4
5
6
7
8
9
Trace =  15.0

Example 7.6, page no. 233

In [51]:
import numpy

def read_mat(a, m, n):
    for i in range(m):
        for j in range(n):
            a[i][j] = int(raw_input())
def write_mat(a, m, n):
    for i in range(m):
        for j in range(n):
            print "%d" %a[i][j],
        print ""

a = numpy.zeros((10, 10))
b = numpy.zeros((10, 10))
c = numpy.zeros((10, 10))

print "Input row & column of A matrix: "
n = int(raw_input("row: "))
m = int(raw_input("column: "))

print "Input row & column of b matrix: "
k = int(raw_input("row: "))
q = int(raw_input("column: "))

if n == k:
    print "Matrices can be multiplied"
    print "Resultant Matrix is %d x %d" %(m, q)
    print "Input A matrix"
    read_mat(a, m, n)
    print "Input B matrix"
    read_mat(b, k, q)
    for i in range(m):
        for j in range(q):
            c[i][j] = 0
            for ip in range(n):
                c[i][j] = c[i][j]+a[i][ip]*b[ip][j]
    print "Resultant of A and B matrices: "
    write_mat(c, m, q)
else:
    print "col of matrix A must be equal to row of matrix B"
    print "Matrices cannot be multiplied"
Input row & column of A matrix: 
row: 3
column: 3
Input row & column of b matrix: 
row: 3
column: 3
Matrices can be multiplied
Resultant Matrix is 3 x 3
Input A matrix
1
2
3
4
5
6
7
8
9
Input B matrix
1
2
3
4
5
6
7
8
9
Resultant of A and B matrices: 
30 36 42 
66 81 96 
102 126 150 

Example 7.7, page no. 235

In [55]:
import numpy

a = numpy.zeros((10, 10))

print "Input row & column of A matrix: "
n = int(raw_input("row: "))
m = int(raw_input("column: "))

print "Input A matrix: "
for i in range(n):
    for j in range(m):
        a[i][j] = int(raw_input())
print "Transpose of matrix A is"
for i in range(m):
    for j in range(n):
        print "%5d" %a[j][i],
    print ""
Input row & column of A matrix: 
row: 3
column: 4
Input A matrix: 
1
2
3
4
5
6
7
8
9
6
7
8
Transpose of matrix A is
    1     5     9 
    2     6     6 
    3     7     7 
    4     8     8 

Example 7.8, page no. 237

In [57]:
strc = "This is a string literal"
print strc
This is a string literal

Example starray.c, page no. 238

In [59]:
names = ["Tejaswi",
         "Prasad",
         "Prasanth",
         "Prakash",
         "Anand",]
for name in names:
    print name
Tejaswi
Prasad
Prasanth
Prakash
Anand

Example strcat.c, page no. 239

In [63]:
oneString = "Fish"
twoString = "face"
oneString += twoString
print oneString
Fishface

Example 7.9, page no. 241

In [73]:
a = []
print "Size of vector ?"
n = int(raw_input())
num = n
print "Vector Elements ?"
for i in range(n):
    a.append(float(raw_input()))
a = set(a)
a = list(a)
length = len(a)
print length
if length == n:
    print "No duplicates found"
else:
    print "Vector has %d duplicates" %(num - length)
    print "Vector after deleting duplicates: ",
    for ele in a:
        print ele,
Size of vector ?
6
Vector Elements ?
1
2
1
3
4
2
4
Vector has 2 duplicates
Vector after deleting duplicates:  1.0 2.0 3.0 4.0

Example 7.10, page no. 242

In [85]:
import numpy

grade = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
a = numpy.zeros((50,10))
print "Number of students ?",
n = int(raw_input())
for i in range(n):
    sum = 0.0
    print "Enter 3 socres of student %d" %(i+1)
    for j in range(3):
        a[i][j] = (float(raw_input()))
        sum += a[i][j]
    avg = sum/3
    a[i][3] = avg
    if avg < 30.0:
        grade[i] = 'E'
    elif avg < 60.0:
        grade[i] = 'D'
    elif avg < 75.0:
        grade[i] = 'B'
    else:
        grade[i] = 'A'
print "S1.no      scores             AVERAGE   GRADE"
print "---------------------------------------------"
for i in range(n):
    print i+1,
    for j in range(4):
        print "%8.2f" %a[i][j],
    print "%6c" %grade[i],
    print ""
    print "---------------------------------------------"
Number of students ?5
 Enter 3 socres of student 1
67
86
58
Enter 3 socres of student 2
20
30
23.9
Enter 3 socres of student 3
80
97
73
Enter 3 socres of student 4
56.8
47.9
62.0
Enter 3 socres of student 5
45
35
40
S1.no      scores             AVERAGE   GRADE
---------------------------------------------
1    67.00    86.00    58.00    70.33      B 
---------------------------------------------
2    20.00    30.00    23.90    24.63      E 
---------------------------------------------
3    80.00    97.00    73.00    83.33      A 
---------------------------------------------
4    56.80    47.90    62.00    55.57      D 
---------------------------------------------
5    45.00    35.00    40.00    40.00      D 
---------------------------------------------

Example 7.11, page no. 243

In [89]:
import math

sumsq = 0
sum = 0
print "Calculation standard deviation of a"
print "Enter size of the list: ",
n = int(raw_input())
x = []
print "Enter the %d items " %n
for i in range(n):
    x.append(float(raw_input()))
    sum += x[i]
mean = sum/n
for i in range(n):
    sumsq = sumsq + (mean-x[i]) * (mean-x[i])
variance = sumsq/n
sdn = math.sqrt(variance)
print "Mean of %5d items     : %10.6f" %(n, mean)
print "Variance               : %10.6f" %(variance)
print "Standard Deviation     : %10.6f" %sdn
Calculation standard deviation of a
Enter size of the list: 7
 Enter the 7 items 
32
11
90
34
52
24
7
Mean of     7 items     :  35.714286
Variance               : 685.918367
Standard Deviation     :  26.190043

Example 7.12, page no. 244

In [90]:
import numpy
import math

def nrm(a, n, m):
    sum = 0.0
    for i in range(n):
        for j in range(m):
            sum = sum + a[i][j] * a[i][j]
    print "Sum = %6.2f" %sum
    return math.sqrt(sum)

a = numpy.zeros((10, 10))
print "Input row & column of A matrix"
n = int(raw_input("row: "))
m = int(raw_input("column: "))
print "Input A matrix"
for i in range(n):
    for j in range(m):
        a[i][j] = float(raw_input())
norm = nrm(a, n, m)
print "Norm = %6.2f" %norm
Input row & column of A matrix
row: 3
column: 3
Input A matrix
1
2
3
4
5
6
7
8
9
Sum = 285.00
Norm =  16.88

Example 7.13, page no. 245

In [91]:
import numpy

a = numpy.zeros((5, 5))
flag = True
print "Input size of matrix"
n = int(raw_input("row: "))
m = int(raw_input("column: "))
print "Enter the elements of the matrix: "
for i in range(m):
    for j in range(n):
        a[i][j] = float(raw_input())
for i in range(m):
    min = a[i][0]
    p = i
    q = 0
    for j in range(n):
        if min > a[i][j]:
            min = a[i][j]
            p = i
            q = j
    for j in range(m):
        if j != q:
            if a[j][q] > a[p][q]:
                flag = False
    if flag:
        print "Saddle point a[%d][%d] = %d" %(p+1, q+1, a[p][q])
    else:
        print "No saddle is in row %d" %(i+1)
    flag = True
Input size of matrix
row: 3
column: 3
Enter the elements of the matrix: 
7
5
5
10
5
8
6
3
3
Saddle point a[1][2] = 5
Saddle point a[2][2] = 5
No saddle is in row 3

Example 7.14, page no. 246

In [96]:
import numpy

a = numpy.zeros((10, 10))
b = numpy.zeros((10, 10))
flag = None
print "Input order of A matrix"
n = int(raw_input("row: "))
print "Input  A matrix"
for i in range(n):
    for j in range(n):
        a[i][j] = int(raw_input())
for i in range(n):
    for j in range(n):
        b[i][j] = a[j][i]
print "Transpose of A matrix"
for i in range(n):
    for j in range(n):
        print "%5d" %b[i][j],
    print ""
for i in range(n):
    for j in range(n):
        if a[i][j] != b[i][j]:
            flag = True
if flag:
    print "Matrix is not symmetric"
else:
    print "Matrix is symmetric"
Input order of A matrix
row: 2
Input  A matrix
1
2
3
4
Transpose of A matrix
    1     3 
    2     4 
Matrix is not symmetric