Chapter 7: Arrays

Example 7.1, Page number: 186

In [40]:
#Print size of various data types using arrays.

import sys

#Variable Initialization
i = [0 for i in range(0,10)]
c = ['0' for i in range(0,10)]
l = [sys.maxint+5 for i in range(0,10)]

#Result
sys.stdout.write("The type 'int' requires %d Bytes"%(sys.getsizeof(int)))
sys.stdout.write("\nThe type 'char' requires %d Bytes"%(sys.getsizeof(str)))
sys.stdout.write("\nThe type 'long' requires %d Bytes"%(sys.getsizeof(long)))
sys.stdout.write("\n%d memory locations are reserved for ten 'int' elements"%(sys.getsizeof(i)))
sys.stdout.write("\n%d memory locations are reserved for ten 'int' elements"%(sys.getsizeof(c)))
sys.stdout.write("\n%d memory locations are reserved for ten 'int' elements"%(sys.getsizeof(l)))

#python data types are different from C
The type 'int' requires 436 Bytes
The type 'char' requires 436 Bytes
The type 'long' requires 436 Bytes
12 memory locations are reserved for ten 'int' elements
100 memory locations are reserved for ten 'int' elements
100 memory locations are reserved for ten 'int' elements

Example 7.2, Page number: 187

In [4]:
#Display character array with their address.

import sys

#Variable Initialization
name = ['A','R','R','A','Y']
i = 0

#Result
sys.stdout.write("\nCharacter Memory Location\n")
while i < len(name):
    sys.stdout.write("\n[%c]\t\t[%d]"%(name[i],id(name[i])))
    i += 1
Character Memory Location

[A]		[31712968]
[R]		[31527832]
[R]		[31527832]
[A]		[31712968]
[Y]		[31712248]

Example 7.3, Page number: 188

In [6]:
#Find sum of even and odd numbers from 1 to 10.  

import sys

#Variable Initialization
sumo = 0
sume = 0
i = 0
a = -1
b = -1

odd = [0 for i in range(0,5)]
even = [0 for i in range(0,5)]

#Calculation
for i in range(1,10+1):
    if i%2 == 0:
        a += 1
        even[a] = i
    else:
        b += 1
        odd[b] = i
    
#Result
sys.stdout.write("\n\tEven  \t\tOdd")
for i in range(0,5):
    sys.stdout.write("\n\t %d\t\t %d"%(even[i],odd[i]))
    sume = sume + even[i]
    sumo = sumo + odd[i]

sys.stdout.write("\n\t==========================\n")
sys.stdout.write("Addition : %d %14d"%(sume,sumo))
        
	Even  		Odd
	 2		 1
	 4		 3
	 6		 5
	 8		 7
	 10		 9
	==========================
Addition : 30             25

Example 7.4, Page number: 189

In [1]:
#Find sum of even numbers and product of odd numbers from 5 input values.

import sys

#Variable Initialization
a = 0
m = 1
num = [0 for i in range(0,5)]

for i in range(0,5):
    sys.stdout.write("\nEnter Number [%d] : "%(i+1))
    num[i] = int(raw_input(""))

#Calculation and Result
sys.stdout.write("\n==================================")
for i in range(0,5):
    if num[i]%2 == 0:
        sys.stdout.write("\nEven Number : %d"%(num[i]))
        a = a + num[i]
    else:
        sys.stdout.write("\nOdd Number : %d"%(num[i]))
        m = m * num[i]

sys.stdout.write("\n==================================")
sys.stdout.write("\nAddition of Even Numbers : %d"%(a))
sys.stdout.write("\nProduct of Odd Numbers : %d"%(m))
sys.stdout.write("\n==================================")
Enter Number [1] : 1

Enter Number [2] : 2

Enter Number [3] : 3

Enter Number [4] : 4

Enter Number [5] : 5

==================================
Odd Number : 1
Even Number : 2
Odd Number : 3
Even Number : 4
Odd Number : 5
==================================
Addition of Even Numbers : 6
Product of Odd Numbers : 15
==================================

Example 7.5, Page number: 190

In [1]:
#Print string in the reverse order.

import sys

#Variable Initialization
s = ['0' for i in range(0,15)]

s = raw_input("Enter a String : \n")

#Result
sys.stdout.write("Reverse String : \n")

#Since there is no null terminating character for string in python, length of string is taken to give the index range
#index range is given -1 to include the index 0 also.

for i in range(len(s)-1,-1,-1):                       
    sys.stdout.write("%c"%s[i])
Enter a String : 
HELLO
Reverse String : 
OLLEH

Example 7.6, Page number: 191

In [2]:
#Detect the occurrence of a character in a given string.

import sys

#Variable Initialization
s = ['0' for i in range(0,15)]
c = 0

s = raw_input("Enter a String : ")
f = raw_input("Enter a Character to Find :")

#Calculation
for i in range(0,len(s)):
    if s[i] == f:
        c += 1
        
#Result
sys.stdout.write("The Character (%c) in a String (%s) occurs %d times."%(f,s,c))
Enter a String : programmer
Enter a Character to Find :r
The Character (r) in a String (programmer) occurs 3 times.

Example 7.7, Page number: 192

In [27]:
#Display the elements of two arrays in two separate columns and add their
#corresponding elements and display in the 3rd column.

import sys

#Variable Initialization
num = [24,34,12,44,56,17]
num1 = [12,24,35,78,85,22]

#Result
sys.stdout.write("Element of Array 1st - 2nd Array  Addition\n")
for i in range(0,5+1):
    sys.stdout.write("\n\t\t%d  +  %d  =   %d"%(num[i],num1[i],num[i]+num1[i]))
Element of Array 1st - 2nd Array  Addition

		24  +  12  =   36
		34  +  24  =   58
		12  +  35  =   47
		44  +  78  =   122
		56  +  85  =   141
		17  +  22  =   39

Example 7.8, Page number: 192

In [1]:
#Find sum of 3 numbers by entering as character type.


import sys

#Variable Initialization
real = [['0' for i in range(0,6)] for i in range(0,6)]
ima = [['0' for i in range(0,6)] for i in range(0,6)]

for l in range(0,3):
    c = int(raw_input("Enter Number : "))
    r = c/255
    i = c%255
    real[l][5] = r
    ima[l][5] = i

c = 0

for l in range(0,3):
    c = c + real[l][5]*255 + ima[l][5]

sys.stdout.write("\nSum of 3 Numbers : %3ld"%(c))
Enter Number : 5
Enter Number : 4
Enter Number : 3

Sum of 3 Numbers :  12

Example 7.9, Page number: 193

In [2]:
#Accept any string upto 15 characters.  Display the elements of string with their
#element numbers in a separate column.

import sys

#Variable Initialization
#name = ['0' for i in range(0,15)]
name = raw_input("Enter your name : ")

#Result
sys.stdout.write("Element no. & Character\n")
for i in range(0,len(name)):                              #There is no null termination character for string in python
    sys.stdout.write("\n%d \t %c"%(i,name[i])) 
Enter your name : amit
Element no. & Character

0 	 a
1 	 m
2 	 i
3 	 t

Example 7.10, Page number: 194

In [3]:
#Display names of days of a week 

import sys

#Variable Initialization
day = [0 for i in range(0,7)]

sys.stdout.write("Enter numbers between 1 to 7 : ")
for i in range(0,6+1):
    day[i] = int(raw_input(""))

#Result
#There is no switch statement in python. use functions and dictionary or if statement instead.
for i in range(0,6+1):
    if day[i] == 1:
        sys.stdout.write("\n%dst day of week is Sunday"%(day[i]))
    else:
        if day[i] == 2:
            sys.stdout.write("\n%dnd day of week is Monday"%(day[i]))
        else:
            if day[i] == 3:
                sys.stdout.write("\n%drd day of week is Tuesday"%(day[i]))
            else:
                if day[i] == 4:
                    sys.stdout.write("\n%dth day of week is Wednesday"%(day[i]))
                else:
                    if day[i] == 5:
                        sys.stdout.write("\n%dth day of week is Thursday"%(day[i]))
                    else:
                        if day[i] == 6:
                            sys.stdout.write("\n%dth day of week is Friday"%(day[i]))
                        else:
                            if day[i] == 7:
                                sys.stdout.write("\n%dth day of week is Saturday"%(day[i]))
                            else:
                                sys.stdout.write("\n%dth is invalid day."%(day[i]))
        
Enter numbers between 1 to 7 : 1
3
2
4
5
7
8

1st day of week is Sunday
3rd day of week is Tuesday
2nd day of week is Monday
4th day of week is Wednesday
5th day of week is Thursday
7th day of week is Saturday
8th is invalid day.

Example 7.11, Page number: 195

In [4]:
#Display the contents of two arrays where the 1st array should contain the string and 2nd numerical numbers.

import sys

#Variable Initialization
city = ['N','A','N','D','E','D']
pin = [4,3,1,6,0,3]

#Result
for i in city:
    sys.stdout.write("%c"%(i))

sys.stdout.write(" - ")
for i in pin:
    sys.stdout.write("%d"%(i))
NANDED - 431603

Example 7.12, Page number: 195

In [5]:
#Display the number of days of different months of year.

import sys

#Variable Initialization
month = [31,28,31,30,31,30,31,31,30,31,30,31]

#Result
for i in range(0,11+1):
    sys.stdout.write("\nMonth [%d] of a year contains %d days."%(i+1,month[i]))
Month [1] of a year contains 31 days.
Month [2] of a year contains 28 days.
Month [3] of a year contains 31 days.
Month [4] of a year contains 30 days.
Month [5] of a year contains 31 days.
Month [6] of a year contains 30 days.
Month [7] of a year contains 31 days.
Month [8] of a year contains 31 days.
Month [9] of a year contains 30 days.
Month [10] of a year contains 31 days.
Month [11] of a year contains 30 days.
Month [12] of a year contains 31 days.

Example 7.13, Page number: 197

In [2]:
#Display the number of days of given month of a year.

import sys

#Variable Initialization
month = [1,3,5,7,8,10,12,4,6,9,11,2]

mn = int(raw_input("Enter Number of Month : "))

for i in range(0,11+1):
    if mn == month[i]:                #There is no goto statement in python
        if i+1 == 12:
            sys.stdout.write("Month (%d) Contains 28 days."%(month[i]))
        if i+1 < 8:
            sys.stdout.write("Month (%d) Contains 31 days."%(month[i]))
        if i+1 > 7 and i+1 != 12:
            sys.stdout.write("Month (%d) Contains 30 days."%(month[i]))
Enter Number of Month : 2
Month (2) Contains 28 days.

Example 7.14, Page number: 198

In [4]:
#Find the average sales of an item out of 12 months sale.

import sys

#Variable Initialization
#Since sum is a built in function in python, sum1 is used instead of sum.
sum1 = 0
avg = 0

sys.stdout.write("Enter Month No.- Sale of an Item/month\n")

item = [0 for i in range(0,11+1)]
for sale in range(0,11+1):
    item[sale] = int(raw_input("\t%d = "%(sale+1)))

#Calculation
for sale in range(0,11+1):
    sum1 = sum1 + item[sale]

avg = sum1/12.0

#Result
sys.stdout.write("\nAverage Sale if an item/month = %f"%(avg))
Enter Month No.- Sale of an Item/month
	1 = 125
	2 = 225
	3 = 325
	4 = 425
	5 = 525
	6 = 625
	7 = 725
	8 = 825
	9 = 925
	10 = 500
	11 = 600
	12 = 700

Average Sale if an item/month = 543.750000

Example 7.15, Page number: 199

In [5]:
#Find the similar elements in an array and find the occurrence of similar
#numbers for number of times.

import sys

#Variable Initialization
k = 0
j = 1

item = [0 for i in range(0,4+1)]
sys.stdout.write("\nEnter Numbers.\n")
for i in range(0,4+1):
    item[i] = int(raw_input("%d = "%(i)))

#Calculation & Result
for j in range(0,4+1):
    for i in range(j+1,4+1):
        if item[j] == item[i]:
            sys.stdout.write("\n%d %d Elements are same."%(j,i))
            k += 1

if k == 10:
    sys.stdout.write("\nAll elements are same")
else:
    if k == 0:
        sys.stdout.write("\nNo Elements are same.")
    else:
        sys.stdout.write("\nElements Contains Double Numbers.")
Enter Numbers.
0 = 5
1 = 8
2 = 3
3 = 5
4 = 9

0 3 Elements are same.
Elements Contains Double Numbers.

Example 7.16, Page number: 200

In [18]:
#Calculate and display total cost of 4 models of Pentium PCs.

import sys

#Variable Initialization
pccode = [1,2,3,4]
t = 0
price = [25000,30000,35000,40000]
stock = [25,20,15,20]

#Result
sys.stdout.write("\nStock & Total Cost Details")
sys.stdout.write("\n========================================================")
sys.stdout.write("\nModel\t\tQty.\tRate(Rs.)\tTotal Value")
sys.stdout.write("\n========================================================")

for i in range(0,3+1):
    sys.stdout.write("\nPentium%d\t%d\t%8ld  %15ld"%(pccode[i],stock[i],price[i],price[i]*stock[i]))
    t = t + price[i] * stock[i]

sys.stdout.write("\n========================================================")
sys.stdout.write("\nTotal Value of All PCs in Rs. %ld"%(t))
sys.stdout.write("\n========================================================")
Stock & Total Cost Details
========================================================
Model		Qty.	Rate(Rs.)	Total Value
========================================================
Pentium1	25	   25000           625000
Pentium2	20	   30000           600000
Pentium3	15	   35000           525000
Pentium4	20	   40000           800000
========================================================
Total Value of All PCs in Rs. 2550000
========================================================

Example 7.17, Page number: 201

In [21]:
#Display the given message by using putc() and stdout() functions.

import sys

#Variable Initialization
msg = "C is Easy"
i = 0

#Result
#There is no putc function and null termination in python.
while i < len(msg):
    sys.stdout.write("%c"%(msg[i]))
    i += 1
C is Easy

Example 7.18, Page number: 202

In [6]:
#Read the text through keyboard and display it by using
#stdin and stdout streams.

import sys

#Variable Initialization
ch = raw_input("Input a Text : ")

#Result
sys.stdout.write("The Text Entered was\n")

for i in ch:
    sys.stdout.write("%c"%(i))
Input a Text : Hello World
The Text Entered was
Hello World

Example 7.19, Page number: 202

In [7]:
#Sort the given strings alphabetically.

import sys

#Variable Initialization
text = raw_input("Enter Text Below : ")

#Result
sys.stdout.write("Sorted Text Below : \n")
for i in range(65,90+1):
    for j in range(0,len(text)):
        if text[j] == chr(i).upper() or text[j] == chr(i).lower():
            sys.stdout.write("%c"%(text[j]))
Enter Text Below : Hello
Sorted Text Below : 
eHllo

Example 7.20, Page number: 203

In [8]:
#Arrange the numbers in increasing and decreasing order

import sys

#Variable Initialization
sys.stdout.write("Enter ten numbers : ")
a = [0 for i in range(0,10)]

for i in range(0,10):
    a[i] = int(raw_input(""))
sum1 = 0

#Calculation
sum1 = sum(a)

#Result
sys.stdout.write("Numbers In Ascending Order : ")
for i in range(0,sum1):
    for j in range(0,10):
        if i == a[j]:
            sys.stdout.write("%3d"%(a[j]))
        
sys.stdout.write("\nNumbers In Descending Order : ")
for i in range(sum1,0,-1):
    for j in range(0,10):
        if i == a[j]:
            sys.stdout.write("%3d"%(a[j]))
Enter ten numbers : 5
2
1
4
7
9
10
12
9
3
Numbers In Ascending Order :   1  2  3  4  5  7  9  9 10 12
Numbers In Descending Order :  12 10  9  9  7  5  4  3  2  1

Example 7.21, Page number: 205

In [9]:
#Sorting in ascending order by comparison method.

import sys

#Variable Initialization

n = int(raw_input("Enter how many numbers to sort : "))

num = [0 for i in range(0,n)]
for i in range(0,n):
    num[i] = int(raw_input("Enter numbers # %2d  : "%(i+1)))

#Result
sys.stdout.write("The Numbers Entered through keyboard\n")
for i in range(0,n):
    sys.stdout.write("%4d"%(num[i]))
for i in range(0,n-1):
    for j in range(i+1,n):
        if num[i] > num[j]:
            temp = num[i]
            num[i] = num[j]
            num[j] = temp

sys.stdout.write("\nThe Numbers in ascending order\n")
for i in num:
    sys.stdout.write("%4d"%(i))
Enter how many numbers to sort : 5
Enter numbers #  1  : 8
Enter numbers #  2  : 3
Enter numbers #  3  : 2
Enter numbers #  4  : 1
Enter numbers #  5  : 9
The Numbers Entered through keyboard
   8   3   2   1   9
The Numbers in ascending order
   1   2   3   8   9

Example 7.22, Page number: 206

In [10]:
#Evaluate the series contains sum of square of
#numbers from 1 to n.  

import sys

#Variable Initialization
s = 0
sqr = [0 for i in range(0,15)]

n = int(raw_input("Enter value of n : "))

for i in range(0,n):
    sqr[i] = pow(i+1,2)
    
for i in range(0,n):
    sys.stdout.write("%d\n"%(sqr[i]))
    s = s + sqr[i]
    
sys.stdout.write("Sum of square : %d"%(s))
Enter value of n : 4
1
4
9
16
Sum of square : 30

Example 7.23, Page number: 207

In [16]:
#Display two dimensional array elements together with their addresses

import sys

#Variable Initialization
a = [[0 for i in range(0,3)]for i in range(0,3)]
c = 1

for i in range(0,3):
    for j in range(0,3):
        a[i][j] = c
        c += 1
        
#Result
sys.stdout.write("Array Elements and addresses.\n")
sys.stdout.write("             Col-0        Col-1         Col-2\n")
sys.stdout.write("========================================================")
sys.stdout.write("\nRow0")

for i in range(0,3):
    for j in range(0,3):
        sys.stdout.write("      %d [%5d]"%(a[i][j],id(a[i][j])))
    sys.stdout.write("\nRow%d"%(i+1))

sys.stdout.write("\r")
Array Elements and addresses.
             Col-0        Col-1         Col-2
========================================================
Row0      1 [6215912]      2 [6215900]      3 [6215888]
Row1      4 [6215876]      5 [6215864]      6 [6215852]
Row2      7 [6215840]      8 [6215828]      9 [6215816]
Row3

Example 7.24, Page number: 208

In [36]:
#Display the elements of two-dimensional array.

import sys

#Variable Initialization
a = [[1,2,3],[4,5,6],[7,8,9]]
        
#Result
sys.stdout.write("Elements of An Array.\n")
for i in range(0,3):
    for j in range(0,3):
        sys.stdout.write("%5d"%(a[i][j]))
    sys.stdout.write("\n")
Elements of An Array.
    1    2    3
    4    5    6
    7    8    9

Example 7.25, Page number: 209

In [11]:
#Read codenos and balance and count the number of codenos, 
#which are having the balance less than 1000.

import sys

#Variable Initialization
j = 0
bal = [[0 for i in range(0,5)]for i in range(0,5)]

for i in range(0,5):
    bal[i][1] = int(raw_input("Enter Code No & Balance : "))
    bal[i][2] = int(raw_input("Enter Code No & Balance : "))
    
sys.stdout.write("Your Entered Data : ")
for i in range(0,5):
    sys.stdout.write("\n%d   %d"%(bal[i][1],bal[i][2]))
    if bal[i][2] < 1000:
        j += 1
        
sys.stdout.write("\nBalance Less than 1000 are %d"%(j))
Enter Code No & Balance : 1
Enter Code No & Balance : 900
Enter Code No & Balance : 2
Enter Code No & Balance : 800
Enter Code No & Balance : 3
Enter Code No & Balance : 1200
Enter Code No & Balance : 4
Enter Code No & Balance : 550
Enter Code No & Balance : 5
Enter Code No & Balance : 600
Your Entered Data : 
1   900
2   800
3   1200
4   550
5   600
Balance Less than 1000 are 4

Example 7.26, Page number: 210

In [12]:
#Accept three elements in a one dimensional array and compute addition,square
#and cube.  Display the results in two dimensional array.

import sys

#Variable Initialization
a = [[0 for i in range(0,3)]for i in range(0,3)]
b = [0 for i in range(0,3)]
j = 0

for i in range(0,3):
    b[i] = int(raw_input("Enter Three Numbers : "))

#Calculation
for i in range(0,3):
    a[i][j] = b[i]*2
    a[i][j+1] = pow(b[i],2)
    a[i][j+2] = pow(b[i],3)
    
#Result
sys.stdout.write("Number\tAddition\tSquare\t\tCube\n")
for i in range(0,3):
    sys.stdout.write("\n%d"%(b[i]))
    for j in range(0,3):
        sys.stdout.write("\t%4d\t"%(a[i][j]))
    sys.stdout.write("\n")
    
Enter Three Numbers : 5
Enter Three Numbers : 6
Enter Three Numbers : 7
Number	Addition	Square		Cube

5	  10		  25		 125	

6	  12		  36		 216	

7	  14		  49		 343	

Example 7.27, Page number: 211

In [14]:
#Read and display matrix

import sys

#Variable Initialization
a = [[0 for i in range(0,10)]for i in range(0,10)]
row = int(raw_input("Enter Order of matrix upto (10x10) A : "))
col = int(raw_input("Enter Order of matrix upto (10x10) A : "))

for i in range(0,row):
    for j in range(0,col):
        a[i][j]  = int(raw_input("Enter Elements of matrix A : "))

#Result
sys.stdout.write("\nThe Matrix is : \n")
for i in range(0,row):
    for j in range(0,col):
        sys.stdout.write("%6d"%(a[i][j]))
    sys.stdout.write("\n")
Enter Order of matrix upto (10x10) A : 3
Enter Order of matrix upto (10x10) A : 3
Enter Elements of matrix A : 3
Enter Elements of matrix A : 5
Enter Elements of matrix A : 8
Enter Elements of matrix A : 4
Enter Elements of matrix A : 8
Enter Elements of matrix A : 5
Enter Elements of matrix A : 8
Enter Elements of matrix A : 5
Enter Elements of matrix A : 4

The Matrix is : 
     3     5     8
     4     8     5
     8     5     4

Example 7.28, Page number: 212

In [15]:
#Transpose of matrix

import sys

#Variable Initialization
a = [[0 for i in range(0,10)]for i in range(0,10)]
b = [[0 for i in range(0,10)]for i in range(0,10)]
row1 = int(raw_input("Enter Order of matrix upto (10x10) A : "))
col1 = int(raw_input("Enter Order of matrix upto (10x10) A : "))

for i in range(0,row1):
    for j in range(0,col1):
        a[i][j]  = int(raw_input("Enter Elements of matrix A : "))
row2 = col1
col2 = row1

#Calculation
for i in range(0,row1):
    for j in range(0,col1):
        b[j][i] = a[i][j]
        
#Result
sys.stdout.write("\nThe Matrix is : \n")
for i in range(0,row2):
    for j in range(0,col2):
        sys.stdout.write("%4d"%(b[i][j]))
    sys.stdout.write("\n")
Enter Order of matrix upto (10x10) A : 3
Enter Order of matrix upto (10x10) A : 3
Enter Elements of matrix A : 3
Enter Elements of matrix A : 5
Enter Elements of matrix A : 8
Enter Elements of matrix A : 4
Enter Elements of matrix A : 8
Enter Elements of matrix A : 5
Enter Elements of matrix A : 8
Enter Elements of matrix A : 5
Enter Elements of matrix A : 4

The Matrix is : 
   3   4   8
   5   8   5
   8   5   4

Example 7.29, Page number: 213

In [16]:
#Transpose of 3x3 matrix

import sys

#Variable Initialization
mat = [[0 for i in range(0,3)]for i in range(0,3)]
for i in range(0,3):
    for j in range(0,3):
        mat[i][j]  = int(raw_input("Enter Elements of matrix "))

#Result
sys.stdout.write("Transpose of the matrix\n")
for i in range(0,3):
    for j in range(0,3):
        sys.stdout.write("\t%d"%(mat[j][i]))
    sys.stdout.write("\n")
Enter Elements of matrix 5
Enter Elements of matrix 8
Enter Elements of matrix 9
Enter Elements of matrix 2
Enter Elements of matrix 5
Enter Elements of matrix 4
Enter Elements of matrix 7
Enter Elements of matrix 5
Enter Elements of matrix 2
Transpose of the matrix
	5	2	7
	8	5	5
	9	4	2

Example 7.30, Page number: 214

In [17]:
#Addition and subtraction of two matrices 

import sys

#Variable Initialization
a = [[0 for i in range(0,10)]for i in range(0,10)]
b = [[0 for i in range(0,10)]for i in range(0,10)]

r1 = int(raw_input("Enter Order of Matrix A & B upto 10x10"))
c1 = int(raw_input("Enter Order of Matrix A & B upto 10x10"))

for i in range(0,r1):
    for j in range(0,c1):
        a[i][j]  = int(raw_input("Enter Elements of Matrix A:"))

for i in range(0,r1):
    for j in range(0,c1):
        b[i][j]  = int(raw_input("Enter Elements of Matrix B:"))

#Calculation and Result
sys.stdout.write("\nMatrix Addition\n")
for i in range(0,r1):
    for j in range(0,c1):
        sys.stdout.write("%5d"%(a[i][j]+b[i][j]))
    sys.stdout.write("\n")

sys.stdout.write("\nMatrix Subtraction\n")
for i in range(0,r1):
    for j in range(0,c1):
        sys.stdout.write("%5d"%(a[i][j]-b[i][j]))
    sys.stdout.write("\n")
Enter Order of Matrix A & B upto 10x103
Enter Order of Matrix A & B upto 10x103
Enter Elements of Matrix A:4
Enter Elements of Matrix A:5
Enter Elements of Matrix A:8
Enter Elements of Matrix A:2
Enter Elements of Matrix A:9
Enter Elements of Matrix A:8
Enter Elements of Matrix A:2
Enter Elements of Matrix A:9
Enter Elements of Matrix A:4
Enter Elements of Matrix B:1
Enter Elements of Matrix B:3
Enter Elements of Matrix B:5
Enter Elements of Matrix B:0
Enter Elements of Matrix B:5
Enter Elements of Matrix B:4
Enter Elements of Matrix B:6
Enter Elements of Matrix B:7
Enter Elements of Matrix B:2

Matrix Addition
    5    8   13
    2   14   12
    8   16    6

Matrix Subtraction
    3    2    3
    2    4    4
   -4    2    2

Example 7.31, Page number: 216

In [18]:
#Multiplication of two matrices 

import sys

#Variable Initialization
a = [[0 for i in range(0,10)]for i in range(0,10)]
b = [[0 for i in range(0,10)]for i in range(0,10)]

r1 = int(raw_input("Enter Order of Matrix A & B upto 10x10"))
c1 = int(raw_input("Enter Order of Matrix A & B upto 10x10"))

for i in range(0,r1):
    for j in range(0,c1):
        a[i][j]  = int(raw_input("Enter Elements of Matrix A:"))

for i in range(0,r1):
    for j in range(0,c1):
        b[i][j]  = int(raw_input("Enter Elements of Matrix B:"))

#Calculation and Result
sys.stdout.write("\nMultiplication of corresponding elements\n")
for i in range(0,r1):
    for j in range(0,c1):
        sys.stdout.write("%5d"%(a[i][j]*b[i][j]))
    sys.stdout.write("\n")
Enter Order of Matrix A & B upto 10x103
Enter Order of Matrix A & B upto 10x103
Enter Elements of Matrix A:4
Enter Elements of Matrix A:5
Enter Elements of Matrix A:8
Enter Elements of Matrix A:2
Enter Elements of Matrix A:9
Enter Elements of Matrix A:8
Enter Elements of Matrix A:2
Enter Elements of Matrix A:9
Enter Elements of Matrix A:4
Enter Elements of Matrix B:1
Enter Elements of Matrix B:3
Enter Elements of Matrix B:5
Enter Elements of Matrix B:0
Enter Elements of Matrix B:5
Enter Elements of Matrix B:4
Enter Elements of Matrix B:6
Enter Elements of Matrix B:7
Enter Elements of Matrix B:2

Multiplication of corresponding elements
    4   15   40
    0   45   32
   12   63    8

Example 7.32, Page number: 217

In [20]:
#Read the Quantity & Price of various Pentium models using an array and
#Compute the total cost of all models.

import sys

#Variable Initialization
pc = [[0 for i in range(0,4)]for i in range(0,4)]
t = 0

for i in range(0,4):
    for j in range(0,2):
        pc[i][j] = int(raw_input("Enter Qty. & Price for Pentium %d : "%(i+1)))

#Result
sys.stdout.write("=====================================================")
sys.stdout.write("\nModel\tQty.\tRate(Rs.)\tTotal Value")
sys.stdout.write("\n=====================================================")
for i in range(0,4):
    sys.stdout.write("\nPentium %d   %2ld %6ld %15ld"%(i+1,pc[i][0],pc[i][1],pc[i][0]*pc[i][1]))
    t = t + pc[i][0] * pc[i][1]

sys.stdout.write("\n=====================================================")
sys.stdout.write("\nTotal Value of All PCs in Rs. %ld"%(t))
sys.stdout.write("\n=====================================================")
Enter Qty. & Price for Pentium 1 : 25
Enter Qty. & Price for Pentium 1 : 25000
Enter Qty. & Price for Pentium 2 : 20
Enter Qty. & Price for Pentium 2 : 40000
Enter Qty. & Price for Pentium 3 : 15
Enter Qty. & Price for Pentium 3 : 35000
Enter Qty. & Price for Pentium 4 : 20
Enter Qty. & Price for Pentium 4 : 40000
=====================================================
Model	Qty.	Rate(Rs.)	Total Value
=====================================================
Pentium 1   25  25000          625000
Pentium 2   20  40000          800000
Pentium 3   15  35000          525000
Pentium 4   20  40000          800000
=====================================================
Total Value of All PCs in Rs. 2750000
=====================================================

Example 7.33, Page number: 218

In [21]:
#Read the capacity of HD, it's price and quantity available in the form of an array
# and compute the cost of HD

import sys

#Variable Initialization
hd = [[0 for i in range(0,4)]for i in range(0,4)]
t = 0

for j in range(0,4):
    for i in range(0,3):
        hd[i][j] = int(raw_input("Enter Capacity, Price & Qty.:"))
        
sys.stdout.write("====================================================================\n")
sys.stdout.write("HD Capacity\tGB Price Rs.\tQuantity Total Value Rs.")
sys.stdout.write("\n====================================================================\n")

for j in range(0,4):
    for i in range(0,3):
        sys.stdout.write("%2ld"%(hd[i][j]))
        sys.stdout.write("\t\t")
        if i == 2:
            sys.stdout.write("%5ld"%(hd[i-1][j]*hd[i][j]))
            t = t + hd[i-1][j] * hd[i][j]
    sys.stdout.write("\n")
    
sys.stdout.write("====================================================================")
sys.stdout.write("\nTotal Value Rs. %37ld"%(t))
sys.stdout.write("\n====================================================================")
Enter Capacity, Price & Qty.:10
Enter Capacity, Price & Qty.:8000
Enter Capacity, Price & Qty.:25
Enter Capacity, Price & Qty.:20
Enter Capacity, Price & Qty.:12000
Enter Capacity, Price & Qty.:20
Enter Capacity, Price & Qty.:40
Enter Capacity, Price & Qty.:15000
Enter Capacity, Price & Qty.:15
Enter Capacity, Price & Qty.:90
Enter Capacity, Price & Qty.:20000
Enter Capacity, Price & Qty.:10
====================================================================
HD Capacity	GB Price Rs.	Quantity Total Value Rs.
====================================================================
10		8000		25		200000
20		12000		20		240000
40		15000		15		225000
90		20000		10		200000
====================================================================
Total Value Rs.                                865000
====================================================================

Example 7.34, Page number: 220

In [45]:
#Display the names of the cities with their base addresses.

import sys

#Variable Initialization
city = ["Mumbai","Chennai","Kolkata","Pune","Delhi"]

#Result
for i in range(0,5):
    sys.stdout.write("Base Address = %u"%(id(city[i])))   #Memory address will differ in different systems
    sys.stdout.write("\tString = %s\n"%(city[i]))
Base Address = 60549024	String = Mumbai
Base Address = 60550048	String = Chennai
Base Address = 60550592	String = Kolkata
Base Address = 60551104	String = Pune
Base Address = 60550240	String = Delhi

Example 7.35, Page number: 220

In [48]:
#Display the binary bits corresponding to Hexadecimal numbers from
#0 to E and attach an odd parity to Hex numbers and display them.

import sys

#Variable Initialization
bin = [[0 for i in range(0,16)]for i in range(0,16)]
a = 0
c = 0

for x in range(0,16):
    y = x
    for a in range(0,4):
        bin[x][a] = y%2
        y = y/2
        
#Result
sys.stdout.write("\nInput Bits\t Parity Bits")
sys.stdout.write("\n===================================")

for x in range(0,16):
    c = 0
    sys.stdout.write("\n")
    for y in range(3,0-1,-1):
        sys.stdout.write("%3d"%(bin[x][y]))
        if bin[x][y] == 1:
            c += 1
    if c%2 == 0:
        sys.stdout.write("%7d"%(1))
    else:
        sys.stdout.write("%7d"%(0))
Input Bits	 Parity Bits
===================================
  0  0  0  0      1
  0  0  0  1      0
  0  0  1  0      0
  0  0  1  1      1
  0  1  0  0      0
  0  1  0  1      1
  0  1  1  0      1
  0  1  1  1      0
  1  0  0  0      0
  1  0  0  1      1
  1  0  1  0      1
  1  0  1  1      0
  1  1  0  0      1
  1  1  0  1      0
  1  1  1  0      0
  1  1  1  1      1

Example 7.36, Page number: 222

In [3]:
#Convert binary to gray codes.

import sys

#Variable Initialization
bin1 = [[0 for i in range(0,16)]for i in range(0,16)]
a = 0
c = 0

#Calculation
for x in range(0,16):
    y = x
    for a in range(0,4):
        bin1[x][a] = y%2
        y = y/2
        
#Result
sys.stdout.write("\nBinary Bits\tGray Bits")
sys.stdout.write("\n==================================")

for x in range(0,16):
    sys.stdout.write("\n")
    for y in range(3,0-1,-1):
        sys.stdout.write("%3d"%(bin1[x][y]))
    sys.stdout.write("%5d   %2d   %2d   %2d"%(bin1[x][3],(bin1[x][3]^bin1[x][2]),(bin1[x][2]^bin1[x][1]),(bin1[x][1]^bin1[x][0])))
Binary Bits	Gray Bits
==================================
  0  0  0  0    0    0    0    0
  0  0  0  1    0    0    0    1
  0  0  1  0    0    0    1    1
  0  0  1  1    0    0    1    0
  0  1  0  0    0    1    1    0
  0  1  0  1    0    1    1    1
  0  1  1  0    0    1    0    1
  0  1  1  1    0    1    0    0
  1  0  0  0    1    1    0    0
  1  0  0  1    1    1    0    1
  1  0  1  0    1    1    1    1
  1  0  1  1    1    1    1    0
  1  1  0  0    1    0    1    0
  1  1  0  1    1    0    1    1
  1  1  1  0    1    0    0    1
  1  1  1  1    1    0    0    0

Example 7.37, Page number: 224

In [54]:
#working of three dimensional array.

import sys

#Variable Initialization
array_3d = [[[0 for i in range(0,3)]for i in range(0,3)]for i in range(0,3)]

for a in range(0,3):
    for b in range(0,3):
        for c in range(0,3):
            array_3d[a][b][c] = a+b+c

#Result
for a in range(0,3):
    sys.stdout.write("\n")
    for b in range(0,3):
        for c in range(0,3):
            sys.stdout.write("%3d"%(array_3d[a][b][c]))
        sys.stdout.write("\n")
  0  1  2
  1  2  3
  2  3  4

  1  2  3
  2  3  4
  3  4  5

  2  3  4
  3  4  5
  4  5  6

Example 7.38, Page number: 225

In [56]:
#working of four dimensional array

import sys

#Variable Initialization
array_4d = [[[[0 for i in range(0,2)]for i in range(0,2)]for i in range(0,2)]for i in range(0,2)]

for a in range(0,2):
    for b in range(0,2):
        for c in range(0,2):
            for d in range(0,2):
                array_4d[a][b][c][d] = a+b+c+d
                
#Result
for a in range(0,2):
    sys.stdout.write("\n")
    for b in range(0,2):
        for c in range(0,2):
            for d in range(0,2):
                sys.stdout.write("%3d"%(array_4d[a][b][c][d]))
            sys.stdout.write("\n")
  0  1
  1  2
  1  2
  2  3

  1  2
  2  3
  2  3
  3  4

Example 7.39, Page number: 226

In [22]:
#Read the quantity & rate of certain items using multidimensional
#array.  Calculate total cost by multiplying quantity & rate and offer 2%
#discount on it & display the net amount.

import sys

#Variable Initialization
m = [[[[0 for i in range(0,2)]for i in range(0,2)]for i in range(0,2)]for i in range(0,2)]

for a in range(0,2):
    for b in range(0,2):
        for c in range(0,2):
            for d in range(0,1):
                if a == 0:
                    m[a][b][c][d] = int(raw_input("Enter Quantity & Rate\na=%d b=%d c=%d d=%d"%(a,b,c,d)))
                    m[a][b][c][d+1] = int(raw_input("Enter Quantity & Rate\na=%d b=%d c=%d d=%d"%(a,b,c,d)))
                else:
                    m[a][b][c][d] = m[a-1][b][c][d] * m[a-1][b][c][d+1]
                    m[a][b][c][d+1] = m[a-1][b][c][d] * m[a-1][b][c][d+1] *2/100
            
#Result
sys.stdout.write("\n============================================================\n")
sys.stdout.write("Quantity\tRate\tAmoount\tDiscount(@2%)\tNet Amount\n")
sys.stdout.write("============================================================\n")

for a in range(0,1):
    for b in range(0,2):
        for c in range(0,2):
            for d in range(0,1):
                sys.stdout.write("\n%10ld %10ld"%(m[a][b][c][d],m[a][b][c][d+1]))
                sys.stdout.write("%8ld.00 %6ld.00 %12ld.00"%(m[a+1][b][c][d],m[a+1][b][c][d+1],m[a+1][b][c][d] - m[a+1][b][c][d+1]))
            
sys.stdout.write("\n============================================================")
                
Enter Quantity & Rate
a=0 b=0 c=0 d=025
Enter Quantity & Rate
a=0 b=0 c=0 d=050
Enter Quantity & Rate
a=0 b=0 c=1 d=030
Enter Quantity & Rate
a=0 b=0 c=1 d=060
Enter Quantity & Rate
a=0 b=1 c=0 d=035
Enter Quantity & Rate
a=0 b=1 c=0 d=070
Enter Quantity & Rate
a=0 b=1 c=1 d=040
Enter Quantity & Rate
a=0 b=1 c=1 d=075

============================================================
Quantity	Rate	Amoount	Discount(@2%)	Net Amount
============================================================

        25         50    1250.00     25.00         1225.00
        30         60    1800.00     36.00         1764.00
        35         70    2450.00     49.00         2401.00
        40         75    3000.00     60.00         2940.00
============================================================

Example 7.40, Page number: 227

In [60]:
#Read string from a character array.

import sys

#Variable Initialization
in1 = raw_input("")   #Since in is a keyword in python, in1 is used

#Result
#There is no sscanf() function in python
out = in1
sys.stdout.write("%s\n"%(out))
HELLO

Example 7.41, Page number: 228

In [23]:
#Read integers in character array, convert and assign them to integer
#variable.

import sys

#Variable initialization
in1 = raw_input("Enter Integers : ")

#Result
sys.stdout.write("Value of int x : %s"%(in1))
Enter Integers : 123
Value of int x : 123

Example 7.42, Page number: 229

In [61]:
#use of sprintf()

import sys

#Variable Initialization
a = 10
c = 'C'
p = 3.14

spf = str("%d %c %.2f"%(a,c,p))        #There is no sprintf() function in python
sys.stdout.write("\n%s"%(spf))
10 C 3.14

Example 7.43, Page number: 229

In [13]:
#Complete the string by filling the spaces with appropriate characters

import sys

#Variable Initialization
name = "Mas er ngA SIC"
name1 = ['' for i in range(0,20)]
x = 0

#Result
sys.stdout.write("Mastering ANSI C\n")

while x < len(name):      #There is no null terminating character in python
    if name[x] == ' ':
        n = raw_input("")
        name1[x] = n
    else:
        name1[x] = name[x]
    x += 1
    
sys.stdout.write("%s"%(name1))
Mastering ANSI C
['M', 'a', 's', 't', 'e', 'r', 'i', 'n', 'g', 'A', 'N', 'S', 'I', 'C', '', '', '', '', '', '']
In [ ]: