PYTHON LAB RECORD Engineering Sem 1
PYTHON LAB RECORD Engineering Sem 1
Flowchart:
Result:
Page 1
GE 4107 / Python Programming Laboratory 2023 - 2024
Exp. No: 3 Scientific problem-solving using decision making and looping
DATE :
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
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):
Page 6
GE 4107 / Python Programming Laboratory 2023 - 2024
Output:
Trial Run 1:
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
Page 8
GE 4107 / Python Programming Laboratory 2023 - 2024
Result:
Page 9
GE 4107 / Python Programming Laboratory 2023 - 2024
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)
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
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
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)
Output:
the unique values from the list is
10
20
30
40
Result:
Page 13
GE 4107 / Python Programming Laboratory 2023 - 2024
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
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
Result :
Page 18
GE 4107 / Python Programming Laboratory 2023 - 2024
Expt. No: 9 Sorting
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
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]
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]
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.
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