GE 4107 / Python Programming Laboratory 2023 - 2024
Exp. No: 2 Even or Odd
DATE :
Flowchart:
Result:
Page 1
GE 4107 / Python Programming Laboratory 2023 - 2024
Exp. No: 3 Scientific problem-solving using decision making and looping
DATE :
** 3.1 - Armstrong number **
Program:
num = int(input('Enter a number: '))
#store a copy of this number
temp =num sum=
0 while(num>0):
rem=num%10
sum= sum+rem ** 3
num = num//10
if(temp==sum):
print('The given number is Armstrong number!!')
else:
print('The given number is not an Armstrong number!')
Output:
Trial Run 1
Enter a number: 371
The given number is Armstrong number!!
Trial Run 2
Enter a number: 273
The given number is not an Armstrong number!
Result :
Page 2
GE 4107 / Python Programming Laboratory 2023 - 2024
**3.2. Number Palindrome **
Program:
num =int(input("Enter any number: "))
#store a copy of this number
temp=num
sum=0
while (num>0):
rem=num%10
sum=sum * 10+ rem
num=num//10
if(temp == sum):
print("The given number is palindrome!!")
else:
print("The given number is Not a palindrome!")
Output:
Trial Run1:
Enter any number: 300
The given number is Not a palindrome!
Trial Run 2
Enter any number: 3003
The given number is palindrome!!
Result:
Page 3
GE 4107 / Python Programming Laboratory 2023 - 2024
**3.3 - Perfect Number **
Program:
n = int(input("Enter any number: "))sum = 0
for i in range(1, n):
if(n % i == 0):
sum = sum + i
if (sum == n):
print("The number is a Perfect number!!")
else:
print("The number is not a Perfect number!")
Output:
Trial Run 1:
Enter any number: 28
The number is a Perfect number!!
Trial Run 2
Enter any number: 25
The number is not a Perfect number!
Result:
Page 4
GE 4107 / Python Programming Laboratory 2023 - 2024
Exp no : 4 Simple programming for one dimensional and two-dimensional arrays
DATE : ** 4.1 – Matrix Addition**
Program:
a = []
row=int(input("Enter row of the matrix: "))
col=int(input("Enter column of the matrix: "))
print("Enter Elements for First Matrix: ")
for i in range(row):
a.append([])
for j in range(col):
num = int(input())
a[i].append(num)
b = []
print("Enter Elements for Second Matrix: ")
for i in range(row):
b.append([])
for j in range(col):
b[i].append(int(input()))
c = []
for i in range(row):
c.append([])
for j in range(col):
c[i].append(a[i][j]+b[i][j])
print("\nAddition Result of Two Given Matrix is:")
for i in range(row):
print(c[i])
Output:
Enter row of the matrix: 2
Enter column of the matrix: 2
Enter Elements for First Matrix:
1
2
3
4
Enter Elements for Second Matrix:
5
6
7
8
Addition Result of Two Given Matrix is:
68
10 12
Result:
Page 5
GE 4107 / Python Programming Laboratory 2023 - 2024
** 4.2 – Matrix Multiplication **
Program:
#Row of first matrix should be equal to the column of the second matrix.
row=int(input("Enter No of Rows for 1st Matrix:"))
column=int(input("Enter No of column for 1nd Matrix:"))
row1=int(input("Enter No of Rows for 2nd Matrix:"))
column1=int(input("Enter No of column for 2nd Matrix:"))
if(column==row1):
print('Enter the First Matrix Element One by One :')
X = [[int(input())for j in range(column)] for i in range(row)]
print('Enter the Second Matrix Element One by One :')
Y = [[int(input()) for j in range(column1)] for i in range(row1)]
result = [[0 for j in range(column1)] for i in range(row)]
print("1st Matrix X:",X)
print("2nd Matrix Y:",Y)
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
else:
print("Multiplication is not possible")
Page 6
GE 4107 / Python Programming Laboratory 2023 - 2024
Output:
Trial Run 1:
Enter No of Rows for 1st Matrix:2
Enter No of column for 1nd Matrix:3
Enter No of Rows for 2nd Matrix:3
Enter No of column for 2nd Matrix:2
Enter the First Matrix Element One by One:
2
3
2
3
2
3
Enter the Second Matrix Element One by One:
2
3
2
3
2
3
1st Matrix X: [[2, 3, 2], [3, 2, 3]]
2nd Matrix Y: [[2, 3], [2, 3], [2, 3]]
[14, 21]
[16, 24]
Trial Run 2:
Enter No of Rows for 1st Matrix:2
Enter No of column for 1nd Matrix:3
Enter No of Rows for 2nd Matrix:2
Enter No of column for 2nd Matrix:3
Multiplication is not possible
Result:
Page 7
GE 4107 / Python Programming Laboratory 2023 - 2024
** 4.3 – To find Scalar Matrix, Determinant of a matrix and Matrix Transpose **
Program:
X = [ [ 1,3,5],
[2,4,8],
[13,15,17] ]
scalar =trans = [ [ 0,0,0],
[0,0,0],
[0,0,0] ]
#scalar multiplication matrix
n=int(input("Enter the scalar value to multiply :"))
for i in range (len(X)):
for j in range(len(X)):
scalar[i][j]=X[i][j]*n
print("Scalar matrix :")
for r in scalar:
print(r)
#transpose of a matrix -changing rows to columns and columns to rows
for i in range (len(X)):
for j in range(len(X)):
trans[j][i]=X[i][j]
print("Matrix Transpose is :")
for r in trans:
print(r)
#determinant matrix
a = X[0][0]
b = X[0][1]
c = X[0][2]
d = X[1][0]
e = X[1][1]
f = X[1][2]
g = X[2][0]
h = X[2][1]
i = X[2][2]
det = (a*(e*i - f*h)) - (b*(d*i - f*g)) + (c*(d*h - e*g))
print(“Determinant of a matrix is”,det)
Output:
Enter the scalar value to multiply :3
Scalar matrix :
[3, 9, 15]
[6, 12, 24]
[39, 45, 51]
Matrix Transpose is :[1,
2, 13]
[3, 4, 15]
[5, 8, 17]
Determinant of a matrix is 48
Result:
Page 8
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No: 5 Program to explore string functions and recursive functions
DATE: **5.1 - String Anagram **
Program:
def areAnagram(str1, str2):
# Get lengths of both strings
n1 = len(str1)
n2 = len(str2)
# If length of both strings is not same, then they cannot be anagram
if (n1 != n2):
return 0
# Sort both strings
str1 = sorted(str1)
str2 = sorted(str2)
# Compare sorted strings
for i in range(0, n1):
if (str1[i] != str2[i]):
return 0
return 1
str1 = raw_input("Enter the First String:")
str2 = raw_input("Enter the Second String:”)
#lower() - converts the string to lower case
str1=str1.lower()
str2=str2.lower()
# Function Call
if (areAnagram(str1, str2)):
print("The two strings are anagram of each other")
else:
print("The two strings are not anagram of each other")
Output:
Trial Run 1:
Enter the First String: LISTEN
Enter the Second String: silent
The two strings are anagram of each other
Trial Run 2:
Enter the First String: test
Enter the Second String: set
The two strings are not anagram of each other.
Result:
Page 9
GE 4107 / Python Programming Laboratory 2023 - 2024
** 5.2 - Tower of Hanoi using recursion **
Program:
def TowerOfHanoi(n , source, destination, auxiliary):
if (n==1):
print ("Move disk 1 from source",source,"to destination”,destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n=int(input("Enter the number of disks"))
TowerOfHanoi(n,'A','B','C')
Output:
Enter the number of disks3
Move disk 1 from source A to destination B
Move disk 2 from source A to destination C
Move disk 1 from source B to destination C
Move disk 3 from source A to destination B
Move disk 1 from source C to destination A
Move disk 2 from source C to destination B
Move disk 1 from source A to destination B
Result:
Page 10
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No 6: Functions
DATE: **6.1 - Find mean, median, mode for the given set of numbers in a list**
Program:
def mean(list,n):
get_sum=sum(list)
mean=get_sum / n
return mean
def median(list, n):
if(n%2 == 0):
median1 = list[n//2]
median2 = list[n//2 - 1]
median = (median1 + median2)/2
else:
median = list[n//2]
return median
def mode(list):
fre={}
for i in a:
fre.setdefault(i,0)
fre[i]+=1
hifre=max(fre.values())
high=[]
for n,k in fre.items():
if (k == hifre):
high.append(n)
return high
size=int(input("Enter the number of elements:"))
a=[]
for i in range(size):
a.append(int(input("Enter values:")))
print("Mean of the list is",mean(a,size))
print("Median of the list is",median(a,size))
print("Mode of the list is",mode(a))
Output:
Enter the number of elements:5
Enter values:2
Enter values:1
Enter values:3
Enter values:1
Enter values:2
Mean of the list is 1.8
Median of the list is 3
Mode of the list is [2, 1]
Result:
Page 11
GE 4107 / Python Programming Laboratory 2023 - 2024
** 6.2- Write a function dups to find all duplicates in the list**
Program:
def dups (arr):
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
print (arr[j]);
arr = [1, 2, 3, 4, 2, 7, 8, 8, 3]
print("Duplicate elements in given array: ")
dups(arr)
Output:
Duplicate elements in given array:
2
3
8
Result:
Page 12
GE 4107 / Python Programming Laboratory 2023 - 2024
** 6.3 - Write a function unique to find all the unique elements of a list**
Program:
def unique(list1):
# initialize a null list
unique_list = []
# traverse for all elements
for x in list1:
#check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
#print list
for x in unique_list:
print (x)
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from the list is")
unique(list1)
Output:
the unique values from the list is
10
20
30
40
Result:
Page 13
GE 4107 / Python Programming Laboratory 2023 - 2024
**6.4 - Write function to compute gcd, lcm of two numbers**
Program:
def gcd(a,b):
res = 1
for i in range(1,a+1):
if (a%i==0 and b%i==0):
res = i
return res
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
print('HCF or GCD of %d and %d is %d' %(first, second, gcd(first,second)))
lcm = first * second / gcd(first, second)
print('LCM of %d and %d is %d' %(first, second, lcm))
Output:
Enter first number: 20
Enter second number: 35
HCF or GCD of 20 and 35 is 5
LCM of 20 and 35 is 140
Result:
Page 14
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No : 7 Demonstration the use of Dictionaries and tuples
DATE: **7.1- Swap two numbers using tuple assignment **
Program:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)
Output:
Enter the first number: 23
Enter the second number: 32
Numbers before swapping:
First Number: 23
Second Number: 32
Numbers after swapping:
First Number: 32
Second Number: 23
Result:
Page 15
GE 4107 / Python Programming Laboratory 2023 - 2024
**7.2 - count the number of times a character appears in a given string using dictionary**
Program:
st = raw_input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: Programming
P:1
r:2
o:1
g:2
a:1
m:2
i:1
n:1
Result:
Page 16
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No. 8 Implement Searching Operations:
DATE: ** 8.1 – Linear Search **
Program:
alist = []
n =int(input('Enter number of elements in the list: '))
for i in range(n):
x =int(input('Enter the Element: '))
alist.append(x)
e =int(input('Enter the Element to search: '))
pos = 0
for i in range(n):
if (alist[i]==e ):
pos=i
print ('Element is found at position %d in the list' %(pos+1))
break
else:
print ('Element is not found in the list')
Output:
Enter Number of Elements in the list: 3
Enter the Element :23
Enter the Element :45
Enter the Element :67
Enter the Element to search: 45
Element is found at position 2 in the list
Result:
Page 17
GE 4107 / Python Programming Laboratory 2023 - 2024
** 8.2 - BINARY SEARCH**
Program:
data = []
n =int(input('Enter total number of elements in the list: '))
print('Enter the Elements in Ascending Order' )
for i in range(0, n):
x =int(input('Enter the Element: '))
data.append(x)
e=int(input('Enter the Element to search: '))
first = 0
last = n-1
while( first<=last):
mid = (first + last)//2
if(e > data[mid]):
first=mid +1
elif(e < data[mid]):
last = mid - 1
else:
print('Element ',e,' Found at Position ',mid+1)break
else:
print('Element', e, ' is Not Found in the List')
Output
Trail Run 1
Enter Number of Elements in the list: 5
Enter the Elements in Ascending Order
Enter the Element 1 :1
Enter the Element 2 :3
Enter the Element 3 :6
Enter the Element 4 :8
Enter the Element 5 :9
Enter the Element to be Search: 8
Element 8 Found at Position 4
Trail Run 2
Enter Number of Elements in the list: 5
Enter the Elements in Ascending Order
Enter the Element 1 :2
Enter the Element 2 :4
Enter the Element 3 :6
Enter the Element 4 :8
Enter the Element 5 :10
Enter the Element to be Search: 7
Element 10 is Not Found in the list.
Time and Space Complexity:
Algorithm / Best Case Average Case Worst Case
Complexity Complexity Complexity Complexity Space Complexity
Linear Search O(1) O(n) O(n) O(1)
Binary Search O(1) O(log n) O(log n) O(1)
Result :
Page 18
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No: 9 Sorting
DATE: ** 9.1 – Selection Sort **
Program:
data = [ ]
print('Selection Sort :')
n = int(input('Enter Number of Elements in the list: '))
for i in range(0, n):
x = int(input('Enter the Element: '))
data.append(x)
print('Original List :')
print(data)
print('Intermediate Steps: ')
for i in range(0,n-1):
min=data[i]
pos=i
for j in range(i+1,n):
if(data[j]<min):
min=data[j]
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted List : ')
print(data)
Output:
Selection Sort :
Enter Number of Elements in the List: 5
Enter the Element 1 :4
Enter the Element 2 :3
Enter the Element 3 :6
Enter the Element 4 :8
Enter the Element 5 :1
Original List :
[4, 3, 6, 8, 1]
Intermediate Steps :
[1, 3, 6, 8, 4]
[1, 3, 6, 8, 4]
[1, 3, 4, 8, 6]
[1, 3, 4, 6, 8]
Sorted List :
[1, 3, 4, 6, 8]
Result:
Page 19
GE 4107 / Python Programming Laboratory 2023 - 2024
** 9.2- Insertion Sort **
Program:
data = []
print('Insertion Sort: ')
n = int(input('Enter Number of Elements in the List: '))
for i in range(0, n):
x = int(input('Enter the Element: '))
data.append(x)
print('Original List: ')
print(data)
print('Intermediate Steps: ')
for i in range(1,n):
temp= data[i]
j=i-1
while temp<data[j] and j>=0:
data[j+1]=data[j]
j=j-1
data[j+1]=temp
print(data)
print('Sorted List is: ')
print(data)
Output:
Insertion Sort :
Enter Number of Elements in the List: 5
Enter the Element 1 :3
Enter the Element 2 :5
Enter the Element 3 :2
Enter the Element 4 :8
Enter the Element 5 :1
Original List :
[3, 5, 2, 8, 1]
Intermediate Steps :
[3, 5, 2, 8, 1]
[2, 3, 5, 8, 1]
[2, 3, 5, 8, 1]
[1, 2, 3, 5, 8]
Sorted List is:
[1, 2, 3, 5, 8]
Result:
Page 20
GE 4107 / Python Programming Laboratory 2023 - 2024
** 9.3. Merge Sort**
Illustration:
Program:
A = [ ]
print('Merge Sort: ')
n = int(input('Enter Number of Elements in the List: '))
for i in range(0, n):
x = int(input('Enter the Element %d :' %(i+1)))
A.append(x)
print('Original List: ')
print(A)
def Merge(left,right,A):
i=j=k=0
while(i < len(left) and j < len(right)):
if(left[i] < right[j]):
A[k]=left[i]
i=i+1
else:
A[k]=right[j]
j+=1
k+=1
while(i < len(left)):
A[k]=left[i]
i=i+1
k=k+1
while(j < len(right)):
A[k]=right[j]
j=j+1
k=k+1
print('Merging',A)
def MergeSort(A):
print('Splitting',A)
n = len(A)
if(n>1):
mid = n//2
left=A[:mid]
right=A[mid:]
MergeSort(left)
MergeSort(right)
Merge(left,right,A)
MergeSort(A)
print(A)
Page 21
GE 4107 / Python Programming Laboratory 2023 - 2024
Output:
Merge Sort :
Enter Number of Elements in the List: 6
Enter the Element 1 :34
Enter the Element 2 :23
Enter the Element 3 :51
Enter the Element 4 :67
Enter the Element 5 :24
Enter the Element 6 :78
Original List :
[34, 23, 51, 67, 24, 78]
Splitting [34, 23, 51, 67, 24, 78]
Splitting [34, 23, 51]
Splitting [34]
Splitting [23, 51]
Splitting [23]
Splitting [51]
Merging [23, 51]
Merging [23, 34, 51]
Splitting [67, 24, 78]
Splitting [67]
Splitting [24, 78]
Splitting [24]
Splitting [78]
Merging [24, 78]
Merging [24, 67, 78]
Merging [23, 24, 34, 51, 67, 78]
[23, 24, 34, 51, 67, 78]
Time and Space Complexity:
Algorithm / Best Case Time Average Case Worst Case Time
Space Complexity
Complexity Complexity Time Complexity Complexity
Selection Sort O(n^2) O(n^2) O(n^2) O(1)
Insertion Sort O(n) O(n^2) O(n^2) O(1)
Merge Sort O(n log n) O(n log n) O(n log n) O(n)
Result:
Page 22
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No : 10 Find the most frequent words in a text of file using command line arguments
DATE :
Program:
import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if(word not in wordcount):
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
maxFreq=0;
for key in wordcount.keys():
if(wordcount[key]>maxFreq):
maxFreq=wordcount[key]
print('Following are the Most Frequent Words in the Specified File')
for key in wordcount.keys():
if(wordcount[key]==maxFreq):
print(key)
Output
Sample.txt:
This is an apple
This is a banana
Command: (Type in terminal)
#python file.py sample.txt
Following are the Most Frequent Words in the Specified File
This
Is
Result:
Page 23
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt no. 11 Exception handling
DATE:
Program:
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
print ("Out of try, except, else and finally blocks." )
Output:
Trial Run 1
try block
Enter a number: 8
Enter another number: 3
else block
Division = 2.6666666666666665
finally block
Out of try, except, else and finally blocks.
Trial Run 2
try block
Enter a number: 2
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
Result:
Page 24
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No: 12 Implementing GUI using turtle, pygame.
DATE: ** 12.1. - To draw a star using Turtle**
Program:
import turtle
star = turtle.Turtle()
star.right(75)
star.forward(100)
for i in range(4):
star.right(144)
star.forward(100)
turtle.done()
Output:
Result:
Page 25
GE 4107 / Python Programming Laboratory 2023 - 2024
** 12.2 - Simulate bouncing ball using pygame **
Program:
import pygame, sys, time
from pygame.locals import
* from time import *
#initialize pygame
pygame.init()
#set up the display window
screen = pygame.display.set_mode((500, 400))
#Set the caption for the bouncing window as “Bouncingball”.
pygame.display.set_caption("Bouncing Ball")BLACK =
(0, 0, 0)
GREEN = (0, 255, 0)
info = pygame.display.Info()sw
= info.current_w
sh = info.current_hy
= 0
# Initial direction is down
direction = 1
while True:
screen.fill(BLACK)
# Use pygame package to create a green colorcircle
pygame.draw.circle(screen, GREEN ,(250,y), 13, 0)
print ("Drawing at 250,", y)
sleep(.006)
y += directionif y >= sh:
# Changes the direction from down to up
direction = -1
elif y <= 0:
# Changes the direction from up to down
direction = 1
pygame.display.update()
for event in pygame.event.get():if
event.type == QUIT:
pygame.quit()
sys.exit()
Output:
Result:
Page 26