# Chapter 8: Arrays¶

## Example 8.1, Page number: 256¶

In [1]:
from array import *

# Variable declaration
word = array('c', ['H', 'e', 'l', 'l', 'o'])

# Result
print ('The contents of word [] is %s ' % ''.join(word))

The contents of word [] is Hello


## Example 8.2, Page number: 259¶

In [2]:
from array import *

# Variable declaration
marks = [0]*10
avg = 0

# Calculation and result
for i in range (0, 10) :
marks[i] = int(raw_input('Enter value in cell [%d] ' % i))
avg = avg + marks[i]

avg = avg/10
print ('The average marks are %f' % avg)

for i in range (0, 10) :
if marks[i] < avg :
print ('Marks in cell [%d] are %d less than average' % (i, marks[i]))
else :
print ('Marks in cell [%d] are %d above/equal to average' % (i, marks[i]))

Enter value in cell [0] 45
Enter value in cell [1] 78
Enter value in cell [2] 65
Enter value in cell [3] 43
Enter value in cell [4] 56
Enter value in cell [5] 98
Enter value in cell [6] 53
Enter value in cell [7] 82
Enter value in cell [8] 74
Enter value in cell [9] 39
The average marks are 63.000000
Marks in cell [0] are 45 less than average
Marks in cell [1] are 78 above/equal to average
Marks in cell [2] are 65 above/equal to average
Marks in cell [3] are 43 less than average
Marks in cell [4] are 56 less than average
Marks in cell [5] are 98 above/equal to average
Marks in cell [6] are 53 less than average
Marks in cell [7] are 82 above/equal to average
Marks in cell [8] are 74 above/equal to average
Marks in cell [9] are 39 less than average


## Example 8.3, Page number: 261¶

In [3]:
from array import *

# Variable declaration
data = raw_input('Enter the string ')

# Calculation and result
rev_data = reversed (data)

if list (data) == list (rev_data) :
print ('The string %s is a PALINDROME' % data)
else :
print ('The string %s is not a PALINDROME' % data)

Enter the string MADAM
The string MADAM is a PALINDROME


## Example 8.4, Page number: 266¶

In [4]:
from array import *

# Variable declaration
marks = [0]*10
avg = 0

# Function declaration, calculation and result
for i in range (0, 10) :
marks[i] = int(raw_input('Enter value in cell [%d] ' % i))

def average (marks) :
mean = 0
for i in range (0, 10) :
mean = mean + marks[i]
return mean/10

def printdata (marks, avg) :
for i in range (0, 10) :
if marks[i] < avg :
print ('Marks in cell [%d] are %d less than average' % (i, marks[i]))
else :
print ('Marks in cell [%d] are %d above/equal to average' % (i, marks[i]))

avg = average (marks)
print ('The average marks are %f' % avg)
printdata (marks, avg)

Enter value in cell [0] 45
Enter value in cell [1] 78
Enter value in cell [2] 65
Enter value in cell [3] 43
Enter value in cell [4] 56
Enter value in cell [5] 98
Enter value in cell [6] 53
Enter value in cell [7] 82
Enter value in cell [8] 74
Enter value in cell [9] 39
The average marks are 63.000000
Marks in cell [0] are 45 less than average
Marks in cell [1] are 78 above/equal to average
Marks in cell [2] are 65 above/equal to average
Marks in cell [3] are 43 less than average
Marks in cell [4] are 56 less than average
Marks in cell [5] are 98 above/equal to average
Marks in cell [6] are 53 less than average
Marks in cell [7] are 82 above/equal to average
Marks in cell [8] are 74 above/equal to average
Marks in cell [9] are 39 less than average


## Example 8.5, Page number: 273¶

In [5]:
from array import *

# Variable declaration
a = [10, 20, 30, 40, 50]

# Function declaration, calculation and result
def fun (x, y, z) :
x = x + 5
y = y + 10
z[4] = z[4] + 100

for i in range (0, 5) :
print ('The cell [%d] contains %d' % (i, a[i]))
print ('The address of cell [%d] is %x' % (i, id(a[i])))

fun (a[0], a[3], a)
print

for i in range (0, 5) :
print ('The cell [%d] contains %d' % (i, a[i]))
print ('The address of cell [%d] is %x' % (i, id(a[i])))

The cell [0] contains 10
The address of cell [0] is 18bc0c0
The cell [1] contains 20
The address of cell [1] is 18bbfd0
The cell [2] contains 30
The address of cell [2] is 18bbee0
The cell [3] contains 40
The address of cell [3] is 18bc5b8
The cell [4] contains 50
The address of cell [4] is 18bc4c8

The cell [0] contains 10
The address of cell [0] is 18bc0c0
The cell [1] contains 20
The address of cell [1] is 18bbfd0
The cell [2] contains 30
The address of cell [2] is 18bbee0
The cell [3] contains 40
The address of cell [3] is 18bc5b8
The cell [4] contains 150
The address of cell [4] is 18bcaf8


## Example 8.6, Page number: 275¶

In [6]:
from array import *

# Variable declaration
data = raw_input('Enter the string ')

# Function declaration, calculation and result
def revstring (data) :
rev_data = reversed (data)

if list (data) == list (rev_data) :
print ('The string %s is a PALINDROME' % data)
else :
print ('The string %s is not a PALINDROME' % data)

revstring (data)

Enter the string python
The string python is not a PALINDROME


## Example 8.7, Page number: 277¶

In [7]:
from array import *

# Variable declaration
a = [0]*10

# Function declaration, calculation and result
pos = 0
for len in range (0, 10) :
num = int(raw_input('Enter data element no. %d ' % len))

for pos in range (0, len+1) :
if num < a[pos] :
break

i = len
while i>=pos :
a[i] = a[i-1]
i = i-1
a[pos] = num

def printdata (a) :
for i in range (0, 10) :
print ('The data in cell [%d] is %d ' % (i, a[i]))

print
printdata (a)

Enter data element no. 0 45
Enter data element no. 1 78
Enter data element no. 2 65
Enter data element no. 3 43
Enter data element no. 4 56
Enter data element no. 5 98
Enter data element no. 6 53
Enter data element no. 7 82
Enter data element no. 8 74
Enter data element no. 9 39

The data in cell [0] is 39
The data in cell [1] is 43
The data in cell [2] is 45
The data in cell [3] is 53
The data in cell [4] is 56
The data in cell [5] is 65
The data in cell [6] is 74
The data in cell [7] is 78
The data in cell [8] is 82
The data in cell [9] is 98


## Example 8.8, Page number: 279¶

In [8]:
from array import *

# Function declaration, calculation and result
a = []
for i in range (0, 10) :
a.append(int(raw_input('Enter data in cell [%d] ' % i)))
return a

def sortdata (a) :
for p in range (0, 9) :
min = p
for i in range (p, 10) :
if a[min] > a[i] :
min = i
temp = a[p]
a[p] = a[min]
a[min] = temp
return a

def printdata (a) :
for i in range (0, 10) :
print ('The data in cell [%d] is %d ' % (i, a[i]))

a = sortdata (a)
print ('\nThe sorted data is ')
printdata (a)

Enter data in cell [0] 45
Enter data in cell [1] 78
Enter data in cell [2] 65
Enter data in cell [3] 43
Enter data in cell [4] 56
Enter data in cell [5] 98
Enter data in cell [6] 53
Enter data in cell [7] 82
Enter data in cell [8] 74
Enter data in cell [9] 39

The sorted data is
The data in cell [0] is 39
The data in cell [1] is 43
The data in cell [2] is 45
The data in cell [3] is 53
The data in cell [4] is 56
The data in cell [5] is 65
The data in cell [6] is 74
The data in cell [7] is 78
The data in cell [8] is 82
The data in cell [9] is 98


## Example 8.9, Page number: 282¶

In [9]:
from array import *

# Function declaration, calculation and result
a = []
for i in range (0, 10) :
a.append(int(raw_input('Enter data in cell [%d] ' % i)))
return a

def bubble (a) :
for p in range (0, 10) :
for i in range (0, 9-p) :
if a[i] > a[i+1] :
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
return a

def printdata (a) :
for i in range (0, 10) :
print ('The data in cell [%d] is %d ' % (i, a[i]))

a = bubble (a)
print ('\nThe sorted data is ')
printdata (a)

Enter data in cell [0] 45
Enter data in cell [1] 78
Enter data in cell [2] 65
Enter data in cell [3] 43
Enter data in cell [4] 56
Enter data in cell [5] 98
Enter data in cell [6] 53
Enter data in cell [7] 82
Enter data in cell [8] 74
Enter data in cell [9] 39

The sorted data is
The data in cell [0] is 39
The data in cell [1] is 43
The data in cell [2] is 45
The data in cell [3] is 53
The data in cell [4] is 56
The data in cell [5] is 65
The data in cell [6] is 74
The data in cell [7] is 78
The data in cell [8] is 82
The data in cell [9] is 98


## Example 8.10, Page number: 285¶

In [12]:
from array import *

# Function declaration, calculation and result
a = []
for i in range (0, size) :
a.append(int(raw_input('Enter data in cell [%d] ' % i)))
return a

def bubble (a, size) :
for p in range (0, size) :
for i in range (0, size-p-1) :
if a[i] > a[i+1] :
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
return a

def printdata (a, size) :
for i in range (0, size) :
print ('The data in cell [%d] is %d ' % (i, a[i]))

def lsearch (a, key, size) :
for i in range (0, size) :
if a[i] == key :
return i
if i == size :
return -1

size = int(raw_input('Enter the total number of elements '))
a = bubble (a, size)
print ('\nThe sorted array is ')
printdata (a, size)

find = int(raw_input('\nEnter the element to be searched '))
pos = lsearch (a, find, size)

if pos<0 :
else :
print ('\nThe element %d found at position %d ' % (find, pos))

Enter the total number of elements 5
Enter data in cell [0] 45
Enter data in cell [1] 78
Enter data in cell [2] 65
Enter data in cell [3] 34
Enter data in cell [4] 49

The sorted array is
The data in cell [0] is 34
The data in cell [1] is 45
The data in cell [2] is 49
The data in cell [3] is 65
The data in cell [4] is 78

Enter the element to be searched 65

The element 65 found at position 3


## Example 8.11, Page number: 288¶

In [13]:
from array import *

# Function declaration, calculation and result
a = []
for i in range (0, size) :
a.append(int(raw_input('Enter data in cell [%d] ' % i)))
return a

def bubble (a, size) :
for p in range (0, size) :
for i in range (0, size-p-1) :
if a[i] > a[i+1] :
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
return a

def printdata (a, size) :
for i in range (0, size) :
print ('The data in cell [%d] is %d ' % (i, a[i]))

def bsearch (a, key, size) :
first = 0
last = size - 1
mid = (first + last)/2

while (first <= last and a[mid] != key) :
if a[mid] < key :
first = mid + 1
else :
if a[mid] > key :
last = mid - 1
mid = (first + last)/2

if a[mid] == key :
return mid
else :
return -1

size = int(raw_input('Enter the number of elements in the array '))
a = bubble (a, size)
print ('\nThe sorted array is ')
printdata (a, size)

find = int(raw_input('\nPlease enter the element to be searched for '))
pos = bsearch (a, find, size)

if pos<0 :
else :
print ('\nThe element %d found at position %d ' % (find, pos))

Enter the number of elements in the array 5
Enter data in cell [0] 45
Enter data in cell [1] 78
Enter data in cell [2] 65
Enter data in cell [3] 34
Enter data in cell [4] 49

The sorted array is
The data in cell [0] is 34
The data in cell [1] is 45
The data in cell [2] is 49
The data in cell [3] is 65
The data in cell [4] is 78

Please enter the element to be searched for 45

The element 45 found at position 1


## Example 8.12, Page number: 293¶

In [13]:
from array import *

# Function declaration, calculation and result
a = [[0 for y in xrange(5)] for x in xrange(no_of_students)]
per = [0 for x in range(no_of_students)]
avg = 0

for i in range (0, no_of_students) :
print ('\nEnter marks of 5 subjects for Roll no. %d ' % (i+1))

for j in range (0, 5) :
a[i][j] = int(raw_input('Subject %d = ' % (j+1)))
per[i] = per[i] + a[i][j]

per[i] = per[i]/5
avg = avg + per[i]

return a, avg/no_of_students, per

def printdata (a, no_of_students, avg, per) :
for i in range (0, no_of_students) :
print ('\nMarks for Roll no. %d are ' % (i+1))
for j in range (0, 5) :
print a[i][j]
print ('Percentage for Roll no. %d is %f ' % ((i+1), per[i]))

if per[i] < avg :
print ('Below average')
else :
print ('Above average')

no_of_students = int(raw_input('How many students marks do you want to enter '))
a, average, per = readncompute (no_of_students)
print ('\nThe average marks are %f ' % average)
printdata (a, no_of_students, average, per)

How many students marks do you want to enter 3

Enter marks of 5 subjects for Roll no. 1
Subject 1 = 75
Subject 2 = 43
Subject 3 = 51
Subject 4 = 68
Subject 5 = 73

Enter marks of 5 subjects for Roll no. 2
Subject 1 = 49
Subject 2 = 71
Subject 3 = 62
Subject 4 = 53
Subject 5 = 50

Enter marks of 5 subjects for Roll no. 3
Subject 1 = 90
Subject 2 = 82
Subject 3 = 74
Subject 4 = 93
Subject 5 = 89

The average marks are 68.000000

Marks for Roll no. 1 are
75
43
51
68
73
Percentage for Roll no. 1 is 62.000000
Below average

Marks for Roll no. 2 are
49
71
62
53
50
Percentage for Roll no. 2 is 57.000000
Below average

Marks for Roll no. 3 are
90
82
74
93
89
Percentage for Roll no. 3 is 85.000000
Above average


## Example 8.13, Page number: 296¶

In [14]:
# Function declaration, calculation and result
def getchoice () :
print
print ('1 - Input two matrices ')
print ('2 - Add and display sum ')
print ('3 - Exit ')

choice = int(raw_input('Enter choice : '))
return choice

def read (matrix, rows, cols) :
for i in range (0, rows) :
print ('\nEnter elements for row %d ' % (i+1))
for j in range (0, cols) :
matrix[i][j] = int(raw_input('matrix[%d][%d] = ' % ((i+1),(j+1))))

for i in range (0, rows) :
for j in range (0, cols) :

def display2matrices (augend, addend, rows, cols) :
print ('\nMatrix A ')
for i in range (0, rows) :
for j in range (0, cols) :
print ('%3d ' % augend[i][j]),
print
print ('\nMatrix B ')
for i in range (0, rows) :
for j in range (0, cols) :
print

def display3matrices (sum, augend, addend, rows, cols) :
print
for i in range (0, rows) :
for j in range (0, cols) :
print ('%3d ' % augend[i][j]),
print ('%s ' % ('+' if i==rows/2 else ' ')),

for j in range (0, cols) :
print ('%s ' % ('=' if i==rows/2 else ' ')),

for j in range (0, cols) :
print ('%2d ' % sum[i][j]),
print

def display (matrix, rows, cols) :
for i in range (0, rows) :
for j in range (0, cols) :
print ('%3d ' % matrix[i][j]),
print

augend = [[0 for y in xrange(10)] for x in xrange(10)]
addend = [[0 for y in xrange(10)] for x in xrange(10)]
sum = [[0 for y in xrange(10)] for x in xrange(10)]

condition = True
while condition :
choice = getchoice ()

if choice == 1 :
rows = int(raw_input('\nEnter the number of rows '))
cols = int(raw_input('Enter the number of columns '))

print ('\n\nEnter the first matrix ')
print ('\n\nEnter the second matrix ')
print ('\n\nYou entered ')

elif choice == 2 :
display3matrices (sum, augend, addend, rows, cols)

elif choice == 3 :
condition = False
exit ()

1 - Input two matrices
2 - Add and display sum
3 - Exit
Enter choice : 1

Enter the number of rows 3
Enter the number of columns 3

Enter the first matrix

Enter elements for row 1
matrix[1][1] = 1
matrix[1][2] = 2
matrix[1][3] = 3

Enter elements for row 2
matrix[2][1] = 3
matrix[2][2] = 4
matrix[2][3] = 5

Enter elements for row 3
matrix[3][1] = 5
matrix[3][2] = 6
matrix[3][3] = 7

Enter the second matrix

Enter elements for row 1
matrix[1][1] = 3
matrix[1][2] = 5
matrix[1][3] = 1

Enter elements for row 2
matrix[2][1] = 6
matrix[2][2] = 5
matrix[2][3] = 3

Enter elements for row 3
matrix[3][1] = 8
matrix[3][2] = 7
matrix[3][3] = 4

You entered

Matrix A
1    2    3
3    4    5
5    6    7

Matrix B
3    5    1
6    5    3
8    7    4

1 - Input two matrices
2 - Add and display sum
3 - Exit
Enter choice : 2

1    2    3      3   5   1      4   7   4
3    4    5  +   6   5   3  =   9   9   8
5    6    7      8   7   4     13  13  11

1 - Input two matrices
2 - Add and display sum
3 - Exit
Enter choice : 3


## Example 8.14, Page number: 300¶

In [3]:
# Function declaration, calculation and result
def readmatrix (matrix, rows, cols) :
for i in range (0, rows) :
print ('\nPlease enter elements for row %d ' % (i+1))
for j in range (0, cols) :
matrix[i][j] = int(raw_input('matrix[%d][%d] = ' % ((i+1),(j+1))))

def multiply (prod, a, b, Ar, Ac, Bc) :
for i in range (0, Ar) :
for j in range (0, Bc) :
prod[i][j] = 0
for k in range (0, Ac) :
prod[i][j] += a[i][k] * b[k][j]

def display (matrix, rows, cols) :
for i in range (0, rows) :
for j in range (0, cols) :
print ('%3d ' % matrix[i][j]),
print

a = [[0 for y in xrange(10)] for x in xrange(10)]
b = [[0 for y in xrange(10)] for x in xrange(10)]
product = [[0 for y in xrange(10)] for x in xrange(10)]

condition = True
while condition  :
Arows, Acols = map(int, raw_input('Enter order of matrix A: ').split())
Brows, Bcols = map(int, raw_input('Enter order of matrix B: ').split())

if Acols == Brows :
condition = False
break
else :
print ('\nMatrices are not compatible for multiplication. Enter the order again. ')
continue

print ('\nEnter matrix A: ')

print ('\nEnter matrix B: ')

multiply (product, a, b, Arows, Acols, Bcols)
print ('\nThe resultant product (A.B) is: ')
display (product, Arows, Bcols)

Enter order of matrix A: 2 3
Enter order of matrix B: 3 2

Enter matrix A:

Please enter elements for row 1
matrix[1][1] = 1
matrix[1][2] = 2
matrix[1][3] = 3

Please enter elements for row 2
matrix[2][1] = 4
matrix[2][2] = 5
matrix[2][3] = 6

Enter matrix B:

Please enter elements for row 1
matrix[1][1] = 6
matrix[1][2] = 5

Please enter elements for row 2
matrix[2][1] = 4
matrix[2][2] = 3

Please enter elements for row 3
matrix[3][1] = 2
matrix[3][2] = 1

The resultant product (A.B) is:
20   14
56   41


## Example 8.15, Page number: 303¶

In [1]:
# Function declaration, calculation and result
def getchoice () :
print
print ('1 - Input square matrix ')
print ('2 - Display upper triangular matrix ')
print ('3 - Display lower triangular matrix ')
print ('4 - Exit ')

condition = True
while condition :
choice = int(raw_input('Enter choice : '))

if choice in range (1, 5) :
condition = False

return choice

def displayupper (matrix, order) :
print
for i in range (0, order) :
for j in range (0, order) :
if j >= i :
print ('%3d ' % matrix[i][j]),
else :
print ('%3d ' % 0),
print

def displaylower (matrix, order) :
print
for i in range (0, order) :
for j in range (0, order) :
if j <= i :
print ('%3d ' % matrix[i][j]),
else :
print ('%3d ' % 0),
print

def read (matrix, rows, cols) :
for i in range (0, rows) :
print ('\nEnter %d elements for row %d ' % (rows, (i+1)))
for j in range (0, cols) :
matrix[i][j] = int(raw_input('matrix[%d][%d] = ' % ((i+1),(j+1))))

matrix = [[0 for y in xrange(10)] for x in xrange(10)]

condition = True
while condition :
choice = getchoice ()

if choice == 1 :
order = int(raw_input('\nEnter order of square matrix '))

elif choice == 2 :
displayupper (matrix, order)

elif choice == 3 :
displaylower (matrix, order)

elif choice == 4 :
condition = False
exit ()

1 - Input square matrix
2 - Display upper triangular matrix
3 - Display lower triangular matrix
4 - Exit
Enter choice : 1

Enter order of square matrix 3

Enter 3 elements for row 1
matrix[1][1] = 1
matrix[1][2] = 2
matrix[1][3] = 3

Enter 3 elements for row 2
matrix[2][1] = 4
matrix[2][2] = 5
matrix[2][3] = 6

Enter 3 elements for row 3
matrix[3][1] = 7
matrix[3][2] = 8
matrix[3][3] = 9

1 - Input square matrix
2 - Display upper triangular matrix
3 - Display lower triangular matrix
4 - Exit
Enter choice : 2

1    2    3
0    5    6
0    0    9

1 - Input square matrix
2 - Display upper triangular matrix
3 - Display lower triangular matrix
4 - Exit
Enter choice : 3

1    0    0
4    5    0
7    8    9

1 - Input square matrix
2 - Display upper triangular matrix
3 - Display lower triangular matrix
4 - Exit
Enter choice : 4


## Example 8.16, Page number: 307¶

In [1]:
# Function declaration, calculation and result
for i in range (0, n) :
print ('\nEnter elements for row no %d ' % (i+1))
for j in range (0, n) :
matrix[i][j] = int(raw_input('matrix[%d][%d] = ' % ((i+1),(j+1))))

def display (matrix, n) :
print
for i in range (0, n) :
for j in range (0, n) :
print ('%5d ' % matrix[i][j]),
print

def isunitmatrix(matrix, n) :
for i in range (0, n) :
if matrix[i][i] != 1 :
return 0

for i in range (0, n) :
for j in range (0, n) :
if i != j :
if matrix[i][j] != 0 :
return 0
return 1

matrix = [[0 for y in xrange(10)] for x in xrange(10)]
n = int(raw_input('Enter order of matrix '))
display (matrix, n)

if (isunitmatrix (matrix, n)) :
print "UNIT MATRIX"
else :
print "NOT A UNIT MATRIX"

Enter order of matrix 3

Enter elements for row no 1
matrix[1][1] = 1
matrix[1][2] = 0
matrix[1][3] = 0

Enter elements for row no 2
matrix[2][1] = 0
matrix[2][2] = 1
matrix[2][3] = 0

Enter elements for row no 3
matrix[3][1] = 0
matrix[3][2] = 0
matrix[3][3] = 1

1      0      0
0      1      0
0      0      1
UNIT MATRIX


## Example 8.17, Page number: 311¶

In [7]:
# Variable declaration
string = raw_input('Enter a string: ')

# Calculation and result
swap_string = string.swapcase()

print swap_string

Enter a string: hello world
HELLO WORLD


## Example 8.18, Page number: 312¶

In [11]:
# Variable declaration
string = raw_input('Enter a string ')

# Function declaration, calculation and result
def printstr (string) :
for i in range (0, len(string)) :
for j in range (0, i+1) :
print string[j],
print

i = i - 2
while i >= 0 :
for j in range (0, i+1) :
print string[j],
print
i = i - 1

printstr (string)

Enter a string hello
h
h e
h e l
h e l l
h e l l o
h e l
h e
h


## Example 8.19, Page number: 314¶

In [9]:
# Variable declaration
a = raw_input('Enter any string ')

# Function declaration, calculation and result
def copy (a) :
b = a
return b

b = copy (a)
print
print ('The first string is %s ' % a)
print ('The second string is %s ' % b)

Enter any string hello

The first string is hello
The second string is hello


## Example 8.20, Page number: 315¶

In [10]:
# Variable declaration
a = raw_input('Enter the major string: ')
b = raw_input('Enter the minor string: ')

# Function declaration, calculation and result
def ispart (a, b) :
if b in a :
print ('The string "%s" is A SUBSTRING of "%s" ' % (b, a))
else :
print ('The string "%s" is NOT A SUBSTRING of "%s" ' % (b, a))

ispart (a, b)

Enter the major string: python is a programming language
Enter the minor string: python
The string "python" is A SUBSTRING of "python is a programming language"