You are on page 1of 6

Siddaganga Institute of Technology

(An autonomous institution affiliated to VTU, Belagavi, Approved by AICTE, New Delhi, Accredited
by NAAC with 'A++' grade & ISO 9001:2015 Certified)

Department of Computer Science & Engineering


(Program Accredited by NBA)

Python Programming Lab3 Exercise Solutions


I. Programs on NumPy arrays.
1. Develop a program to read the salaries of employees in a NumPy array of
‘float64’, initialized with zeros in the beginning.
Then do the following:
1. Allow the user to edit particular employee salary to add increment or an
incentive.
2. Display both old and updated salaries in ascending order using copy() and
sort() .
3. Display the first ‘n’ salaries
4. Display the last ‘n’ salaries.
5. Display the salaries of the employees in a given range of indices ‘m’- ‘n’.
Soln. import numpy as np
no_emp= int (input('enter the number of employees'))
#initialize a salaries array to zeros
salaries = np.zeros(no_emp, dtype='float64')
#read salaries in it
for i in range(no_emp):
print("Enter salary for employee",i)
salaries[i]=float(input())
print("Salaries are:")
print(salaries)

#copy()
oldsalaries=np.copy(salaries)

#edit salary of an employee


print("enter the index of employee in 0 to ",no_emp-1)

index= int(input())

#check for a valid index value


while index >no_emp-1 or index<0:
print('Kindly enter the proper index value')
index= int(input())
increment= float(input('enter the increment to be added'))
salaries[index]+=increment
print('------------------------------------')
print('updated salaries are:')
print(salaries)

#sort()
np.sort(oldsalaries)
np.sort(salaries)
print('------------------------------------')
print('Sorted salaries are:')
print('old Salaries:',oldsalaries)
print('Current Salaries:',salaries)

#Display the first ‘n’ salaries


print('enter the a value upto ',no_emp)
n= int(input())
print('------------------------------------')
print("first ",n,"salaries are:")
print(salaries[:n])

#Display the last ‘n’ salaries.


print('enter the a value upto ',no_emp)
n= int(input())
print('------------------------------------')
print("Last ",n,"salaries are:")
print(salaries[n:])

#Display the salaries of the employees in a given range of indices ‘m’- ‘n’.
print('enter a valid range in 0-',no_emp-1)
m,n = input().split()
print('------------------------------------')
print("salaries in range:",m,"to",n,"are:")
print(salaries[int(m):int(n)])
2. Develop a program to read marks of two sections of a class using NumPy arrays.
Then do the following using the b
uilt-in functions:
i. Display the marks of whole class by merging the details (use
concatenate()).
ii. Display the marks of a student searched using searchsorted().

Soln. import numpy as np


sst1= int (input('enter the first section strength'))
#initialize a array to zeros
sect1_USNs = np.zeros(sst1, dtype='int16')
sect1_Marks = np.zeros(sst1, dtype='int16')
#read marks and usns
for i in range(sst1):
print("Enter USN and Marks of student ",i)
sect1_USNs[i]=int(input('USN:'))
sect1_Marks[i]=int(input("MARKS:"))
print("Section 1 student details are:")
print(sect1_USNs)
print(sect1_Marks)
print('------------------------------')
sst2= int (input('enter the second section strength'))
#initialize a array to zeros
sect2_USNs = np.zeros(sst2, dtype='int16')
sect2_Marks = np.zeros(sst2, dtype='int16')
#read marks and usns
for i in range(sst2):
print("Enter USN and Marks of student ",i)
sect2_USNs[i]=int(input('USN:'))
sect2_Marks[i]=int(input("MARKS:"))
print('------------------------------')
print("Section 2 student details are:")
print(sect2_USNs)
print(sect2_Marks)
print('------------------------------')
print('whole class details are:')
whole_USNs=np.concatenate((sect1_USNs,sect2_USNs),axis=0)
whole_Marks=np.concatenate((sect1_Marks,sect2_Marks),axis=0)
print(whole_USNs)
print(whole_Marks)
print('------------------------------')
usn = int(input('enter the usn to be searched'))
"""
searchsorted function:
i. works only on 1D arrays
ii.works only on sorted arrays as it uses binary search
iii.Gets index where the key is found
iv. if key is not found then it returns 0 if Key< first element else it returns the
length of the array when key>last element of the array

"""
std= np.searchsorted(whole_USNs,usn)

if std>=0 and std<len(whole_USNs):


if std==0:
if usn != whole_USNs[0]:
print('UsN Not found')
else:
print('UsN found')
print('Marks are:',whole_Marks[std])
else:
print('UsN Not found')
3. Develop a menu driven program with NumPy arrays to do the following:
1. Display first n numbers divisible 6.
2. Display values in a range up to ‘n’.
3. Display values of an array falling below a ‘x’ value
4. Display values of the array falling in a given range ‘m’ and ‘n’.
5. Display the indices of the values that are above a threshold
Soln. import numpy as np
arr=np.array([10,20,30,40,50,60],dtype=int)
while 1:
print('enter 1--> Display first n numbers divisible by 6')
print('2 --> Display values in a range up to ‘n’')
print('3 --> Display values of an array falling below a ‘x’ value')
print('4 --> Display values of the array falling in a given range ‘m’ and ‘n’')
print('5 --> Display the indices of the values that are above a threshold')
print('6 --> for exit')
ch=int(input('enter the choice'))
if ch==1:
print('---------------------------------------------------')
print('array elements divisible by 6 are:',arr[arr%6==0])
print('---------------------------------------------------')
elif ch==2:
print('---------------------------------------------------')
n=int(input('enter n value '))
print('array elements in range',n,' are:',arr[:n])
print('---------------------------------------------------')
elif ch==3:
print('---------------------------------------------------')
x=int(input('enter x value '))
print('array elements upto ',x,' are:',arr[arr<=x])
print('---------------------------------------------------')
elif ch==4:
print('---------------------------------------------------')
m,n=input('enter a range ').split()
print('array elements falling in range',m,'and ',n,' are:',arr[(arr>=int(m)) &
(arr<=int(n))])
print('---------------------------------------------------')
elif ch==5:
print('---------------------------------------------------')
n=int(input('enter a threshold '))
print('array elements above ',n,' are:',arr[arr>n])
print('---------------------------------------------------')
else:
break

4. Develop a program to do following on matrices using NumPy arrays:


i. Read a matrix
ii. Display a matrix
iii. Multiply a matrix elements with a value ‘x’ and display the same
iv. Display the odd and even numbers in a matrix separately as 2 arrays.
v. Count all elements greater than a value ‘x’
Soln. import numpy as np
#accept order at once
m,n=input('enter the order of the matrix').split()
#define matrix of order mXn
mat = np.zeros((int(m),int(n)),dtype='int32')

#read matrix
for i in range(0,int(m)):
print('enter ',n,'elements separated by space')
mat[i]=input().split()

#display matrix
print('---------------------------------------------------')
print('the matrix is ',mat)

#Multiply a matrix elements with a value ‘x’ and display the same
print('---------------------------------------------------')
a=int(input('enter a value'))
print('array after multiplication')
print(mat*a)

#Display the odd and even numbers in a matrix separately as 2 arrays.


print('---------------------------------------------------')
print('Odd elements of the matrix :')
odd= mat[mat%2!=0]
print(odd)
print('Even elements of the matrix :')
even=mat[mat%2==0]
print(even)

#Count all elements greater than a value ‘x’


print('---------------------------------------------------')
n=int(input('enter a value'))
arr=mat[mat>n]
print("the count of maytrix elements >",n,'is ',len(arr))
5. Develop a program to perform the following operations on two matrices using
NumPy arrays:
1. Display sum of them
2. Display difference of them
3. Merge and display the matrices.
4. Multiply the matrices.

Soln. import numpy as np


#accept order of m1 at once
m1,n1=input('enter the order of the matrix').split()
#define matrix of order mXn
mat1 = np.zeros((int(m1),int(n1)),dtype='int32')

#read matrix
for i in range(0,int(m1)):
print('enter ',n1,'elements separated by space')
mat1[i]=input().split()

#accept order of m2 at once


m2,n2=input('enter the order of the matrix').split()
#define matrix of order mXn
mat2 = np.zeros((int(m2),int(n2)),dtype='int32')
#read matrix
for i in range(0,int(m2)):
print('enter ',n2,'elements separated by space')
mat2[i]=input().split()
#display matrices
print('---------------------------------------------------')
print('the matrix1 is\n ',mat1)
print('---------------------------------------------------')
print('the matrix2 is \n ',mat2)
#Display sum of them
if m1== m2 and n1==n2:
print('---------------------------------------------------')
print('the sum of the matrices is \n ',mat1+mat2)
#Display difference of them
print('---------------------------------------------------')
print('the differen of the matrices is \n ',mat1-mat2)
#Merge and display the matrices.
print('---------------------------------------------------')
i = int(input('enter 0 to merge vertically and 1 to merge horizontally'))
if i==0:
print('Vertically merged matrices result \n ' ,
np.concatenate((mat1,mat2),axis=0))
elif i==1:
print('Horizontally merged matrices result \n ' ,
np.concatenate((mat1,mat2),axis=1))
else:
print("invalid choice of merge")
else:
print('---------------------------------------------------')
print('the sum ,difference and merge of the matrices is not possible \n ')

#Multiply the matrices.


if n1==m2:
print('---------------------------------------------------')
print('the product of the matrices is :\n',np.matmul(mat1,mat2))
else:
print('---------------------------------------------------')
print('the product of the matrices is not possible :\n')

You might also like