HINDUSTHAN COLLEGE OF ARTS AND SCIENCE
(AUTONOMOUS)
An Autonomous Institution - Affiliated to Bharathiar University
(ISO 9001-2001 Certified Institution)
Behind Nava India, Coimbatore – 641028.
PG AND RESEARCH DEPARTMENT OF COMPUTER APPLICATIONS
MASTER OF COMPUTER APPLICATIONS
PRACTICAL RECORD
20MCP20 PRACTICAL V – PYTHON PROGRAMMING LAB
NAME : __________________________
REGISTER NO : __________________________
CLASS : __________________________
SEMESTER : __________________________
YEAR : __________________________
HINDUSTHAN COLLEGE OF ARTS AND SCIENCE
(AUTONOMOUS)
An Autonomous Institution - Affiliated to Bharathiar University
(ISO 9001-2001 Certified Institution)
Behind Nava India, Coimbatore – 641028
PG AND RESEARCH DEPARTMENT OF COMPUTER APPLICATIONS
CERTIFICATE
Certified that this is a bonafide record of
PYTHON PROGRAMMING LAB (20MCP20) done
by_____________ Register no:________________ during the academic year 2020-2021.
DIRECTOR STAFF-IN CHARGE
Submitted for the Bharathiar University practical Examination held on
_____________at Hindusthan College of Arts and Science, Coimbatore - 28.
INTERNAL EXAMINER EXTERNAL EXAMINER
Date:
Place: Coimbatore
CONTENTS
S.NO DATE NAME OF THE PROGRAM PAGE.NO SIGN
1 GCD OF TWO NUMBERS 1
2 TOWERS OF HANOI USING RECURSION 4
MAXIMUM AND MINIMUM VALUE IN BINARY
3 7
SEARCH TREE
4 SIMPLE MATRIX OPERATION 11
5 LINEAR AND BINARY SEARCH 17
CALCULATE SUM OF ROWS, COLUMNS AND
6 21
DIAGONALS USING 2D ARRAY
INSERTION OPERATION USING SINGLY LINKED
7 25
LIST
8 COMMAND LINE ARGUMENT (WORD COUNT) 35
DELETION OPERATION USING SINGLY LINKED
9 38
LIST
10 LINE CHART IN MS EXCEL 43
PROGRAM .NO: 1 DATE:
GCD OF TWO NUMBERS
AIM
To compute the GCD of two numbers
ALGORITHM
STEP 1 Start the program
STEP 2 If X=0 then GCD(X, Y)=Y since the Greatest Common Divisor of 0 and Y is
Y.
STEP 3 If Y=0 then GCD(X,Y)=X since the Greatest Common Divisor of 0 and X is
X.
STEP 4 Let R be the remainder of dividing X by Y assuming X > Y. (R = X % Y)
STEP 5 Find GCD( Y, R ) because GCD( X, Y ) = GCD( Y, R ). Use the above steps
again.
STEP 6 Stop the program
1
SOURCE CODE
def gcd_fun (x, y):
if (y == 0):
return x
else:
return gcd_fun (y, x % y)
x =int (input ("Enter the first number: "))
y =int (input ("Enter the second number: "))
num = gcd_fun(x, y)
print("Greatest Common Divisor of the given two numbers is: ")
print(num)
2
OUTPUT
RESULT
The above program is executed and hence captured the necessary output.
3
PROGRAM .NO: 2 DATE:
TOWERS OF HANOI USING RECURSION
AIM
To perform Towers of Hanoi using Recursion
ALGORITHM
STEP 1: Start the Program.
STEP 2: Create Recursive Function.
STEP 3: Call Tower of Hanoi Function Itself again and again.
STEP 4: Initialize function Variables as Source, Auxiliary and target.
STEP 5: Print the Statement.
STEP 6: Refer source as A, auxiliary as B, and target as C
STEP 7: Call the Function Tower of Hanoi as A,B,C.
STEP 8: End the program.
4
SOURCE CODE
# Creating a recursive function
def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
# function call itself
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))
tower_of_hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter the number of disks: '))
# We are referring source as A, auxiliary as B, and target as C
tower_of_hanoi(disks, 'A', 'B', 'C')
# Calling the function
5
OUTPUT
RESULT
The above program is executed and hence captured the necessary output.
6
PROGRAM .NO: 3 DATE:
MAXIMUM AND MINIMUM VALUE IN BINARY SEARCH TREE
AIM
To find a maximum and minimum value in Binary search tree.
ALGORITHM
Approach for finding minimum element:
Traverse the node from root to left recursively until left is NULL.
The node whose left is NULL is the node with minimum value.
Approach for finding maximum element:
Traverse the node from root to right recursively until right is NULL.
The node whose right is NULL is the node with maximum value.
7
SOURCE CODE
#Find minimum and maximum in binary tree using recursion
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def findMax(root):
if (root == None):
return float('-inf')
res = root.data
lres = findMax(root.left)
rres = findMax(root.right)
if (lres > res):
res = lres
if (rres > res):
res = rres
return res
def findMin(root):
if (root == None):
return float('inf')
res = root.data
lres = findMin(root.left)
8
rres = findMin(root.right)
if (lres < res):
res = lres
if (rres < res):
res = rres
return res
if __name__ == '__main__':
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
print("Maximum element is", findMax(root))
print("Minimum element is", findMin(root))
9
OUTPUT
RESULT
The above program is executed and hence captured the necessary output.
10
PROGRAM .NO: 4 DATE:
SIMPLE MATRIX OPERATION
AIM
To Perform simple Matrix operation.
ALGORITHM
STEP 1: Start the Program
STEP 2: Create Class Matrices as:
def __init__(self,A,B):
self.A=A
self.B=B
def display(self,C):
print('Resultant Matrix is:')
for i in range(0,m):
print('\n')
for j in range(0,n):
print(' {}'.format(C[i][j]),end=" ")
STEP 3: Perform Operations for Addition, Subtraction, Multiplication
For Example:
def Add(self,C):
for i in range(0,m):
for j in range(0,n):
C[i][j] = A[i][j] + B[i][j]
STEP 4: Add Statement to Print Number of Rows and Columns in
Matrices A and B.
STEP 5: Using While Loop Provide the choices for Addition,
Subtraction, and Multiplication.
STEP 6: Initialize the Object To call the Function.
STEP 7: End the Program
11
SOURCE CODE
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 12:50:34 2021
@author: Mercy Deepa
"""
class Matrices:
def __init__(self,A,B):
self.A=A
self.B=B
def display(self,C):
print('Resultant Matrix is:')
for i in range(0,m):
print('\n')
for j in range(0,n):
print(' {}'.format(C[i][j]),end=" ")
def Add(self,C):
for i in range(0,m):
for j in range(0,n):
C[i][j] = A[i][j] + B[i][j]
def Sub(self,C):
for i in range(0,m):
12
for j in range(0,n):
C[i][j] = A[i][j] - B[i][j]
def Mul(self,C):
for i in range(0,m):
for j in range(0,q):
for k in range(0,n):
C[i][j]+= A[i][k] * B[k][j]
if __name__=='__main__':
m = int(input('Enter no. of rows for Matrix 1:'))
n = int(input('Enter no. of columns for Matrix 1:'))
A = [[0 for j in range(0, n)] for i in range(0, m)]
print('Enter Elements of Matrix A')
for i in range(0, m):
for j in range(0, n):
A[i][j] = int(input('Enter element A{}{}:'.format(i, j)))
p = int(input('Enter no. of rows for Matrix 2:'))
q = int(input('Enter no. of columns for Matrix 2:'))
B = [[0 for j in range(0, q)] for i in range(0, p)]
print('Enter Elements of Matrix B')
for i in range(0, p):
for j in range(0, q):
B[i][j] = int(input('Enter element B{}{}:'.format(i, j)))
obj = Matrices(A,B)
13
var =1
while var!='0':
print('1.Add Matrices\n2.Subtract Matrices\n3.Multiply Matrices\n4.Exit')
choice = int(input('Enter Choice:'))
if choice==1:
if m==p and n==q:
print('Matrices can be Added')
C = [[0 for j in range(0, n)] for i in range(0, m)]
obj.Add(C)
obj.display(C)
else:
print('Matrices cannot be Added')
elif choice==2:
if m==p and n==q:
print('Matrices can be Subtracted')
C = [[0 for j in range(0, n)] for i in range(0, m)]
obj.Sub(C)
obj.display(C)
else:
print('Matrices cannot be Subtracted')
elif choice==3:
if n==p:
print('Matrices can be Multiplied')
14
C = [[0 for j in range(0, q)] for i in range(0, m)]
obj.Mul(C)
obj.display(C)
else:
print('Matrices cannot be Multiplied')
elif choice==4:
exit(0)
else:
print('\nPlease enter a valid choice')
var = (input('\nDo you want to Continue?(press 0 to stop)'))
15
OUTPUT
RESULT
The above program is executed and hence captured the necessary output.
16
PROGRAM .NO: 5 DATE:
LINEAR AND BINARY SEARCH
AIM
To Perform Linear and Binary search
ALGORITHM
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Step 1 : Start searching data from middle of the list.
Step 2 : If it is a match, return the index of the item, and exit.
Step 3 : If it is not a match, probe position.
Step 4 : Divide the list using probing formula and find the new
middle.
Step 5 : If data is greater than middle, search in higher sub-list.
17
Step 6 : If data is smaller than middle, search in lower sub-list.
Step 7 : Repeat until match
SOURCE CODE
from array import *
def linear_search(arr, n):
for i in range(len(arr)):
if arr[i] == n:
return i
return -1
arr = array('i',[])
n = int (input("LS-No of elements: "))
for i in range(n):
x = int(input("Element: "))
arr.append(x)
num = int (input("search "))
r = linear_search(arr, num)
if(r == -1):
print("LS-Element not found")
else:
print("LS-Element found at index",str(r))
def binary_searchiter(arr2, n):
low = 0
18
high = len(arr2) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr2[mid] < n:
low = mid + 1
elif arr2[mid] > n:
high = mid - 1
else:
return mid
return -1
arr2 = array('i',[])
n = int (input("BS-No of elements: "))
for i in range(n):
x = int(input("Element: "))
arr2.append(x)
number = int (input("search "))
r = binary_searchiter(arr2, number)
if r != -1:
print("Element found at index", str(r))
else:
print("Element is not present in array")
OUTPUT
19
RESULT
The above program is executed and hence captured the necessary output.
20
PROGRAM .NO: 6 DATE:
CALCULATE SUM OF ROWS, COLUMNS AND DIAGONALS USING
TWO-DIMENSIONAL ARRAY
AIM
To Perform simple Matrix operation.
ALGORITHM
Step 1: Start the Program
Step 2: Create Function to Calculate sum of each Row.
Step 3: To find the sum of row:
for i in range(0, n) :
for j in range(n) :
# Add the element
sum += arr[i][j]
Step 4:Print the sum of row and reset the sum as 0.
Step 5: Repeat Step 3 and 4 for sum of column and diagonals by Changing the
elements in FOR loop.
Step 6: Initialize the array elements for Input.
Step 7: Call the Function of Row,Column, and Diagonals.
Step 8: End the program
21
SOURCE CODE
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 12:50:34 2021
@author: Mercy Deepa
"""
# Function to calculate sum of each row
def row_sum(arr, n) :
sum = 0
print("\nFinding Sum of each row:\n----------------------------")
# finding the row sum
for i in range(0, n) :
for j in range(n) :
# Add the element
sum += arr[i][j]
# Print the row sum
print("Sum of the row",i,"=",sum)
# Reset the sum
sum = 0
# Function to calculate sum of each column
def column_sum(arr, n) :
sum = 0
print("\nFinding Sum of each column:\n----------------------------")
# finding the column sum
for i in range(0, n) :
for j in range(n) :
# Add the element
sum += arr[j][i]
# Print the column sum
print("Sum of the column",i,"=",sum)
# Reset the sum
sum = 0
22
# Function to calculate sum of diagnals
def diagonal_sum(arr, n):
principal = 0
secondary = 0
print("\nFinding Sum of diagnals:\n----------------------------")
for i in range(0, n):
principal += arr[i][i]
secondary += arr[i][n - i -1]
print("Principal Diagnal:", principal)
print("Secondary Diagnal:", secondary)
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print("\n")
print("The given matrix is: \n----------------------------\n", arr[0],"\n", arr[1], "\n",
arr[2])
row_sum(arr, 3)
column_sum(arr, 3)
diagonal_sum(arr,3)
OUTPUT
23
RESULT
The above program is executed and hence captured the necessary output.
PROGRAM .NO: 7 DATE:
24
INSERTION OPERATION USING SINGLY LINKED LIST
AIM
To Perform Insertion operation using Singly Linked List
ALGORITHM
Step 1: If Ptr = Null
Write Overflow
Go To Step 7
[End Of If]
Step 2: Set New_Node = Ptr
Step 3: Set Ptr = Ptr → Next
Step 4: Set New_Node → Data = Val
Step 5: Set New_Node → Next = Head
Step 6: Set Head = New_Node
Step 7: Exit
SOURCE CODE
class Node:
25
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
26
def insertAfter(self, prev_node, new_data):
# 1. check if the given prev_node exists
if prev_node is None:
print ("The given previous node must inLinkedList.")
return
# 2. Create new node &
# 3. Put in the data
new_node = Node(new_data)
# 4. Make next of new Node as next of prev_node
new_node.next = prev_node.next
# 5. make next of prev_node as new_node
prev_node.next = new_node
def append(self, new_data):
# 1. Create a new node
# 2. Put in the data
# 3. Set next as None
new_node = Node(new_data)
# 4. If the Linked List is empty, then make the
27
# new node as head
if self.head is None:
self.head = new_node
return
# 5. Else traverse till the last node
last = self.head
while (last.next):
last = last.next
# 6. Change the next of last node
last.next = new_node
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
28
def __init__(self):
self.head = None
# Functio to insert a new node at the beginning
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This function is in LinkedList class. Inserts a
# new node after the given prev_node. This method is
# defined inside LinkedList class shown above */
def insertAfter(self, prev_node, new_data):
# 1. check if the given prev_node exists
if prev_node is None:
29
print ("The given previous node must inLinkedList.")
return
# 2. create new node &
# Put in the data
new_node = Node(new_data)
# 4. Make next of new Node as next of prev_node
new_node.next = prev_node.next
# 5. make next of prev_node as new_node
prev_node.next = new_node
# This function is defined in Linked List class
# Appends a new node at the end. This method is
# defined inside LinkedList class shown above */
def append(self, new_data):
# 1. Create a new node
# 2. Put in the data
# 3. Set next as None
new_node = Node(new_data)
# 4. If the Linked List is empty, then make the
30
# new node as head
if self.head is None:
self.head = new_node
return
# 5. Else traverse till the last node
last = self.head
while (last.next):
last = last.next
# 6. Change the next of last node
last.next = new_node
# Utility function to print the linked list
def printList(self):
temp = self.head
while (temp):
print (temp.data)
temp = temp.next
# Code execution starts here
if __name__=='__main__':
31
# Start with the empty list
llist = LinkedList()
# Insert 6. So linked list becomes 6->None
llist.append(6)
# Insert 7 at the beginning. So linked list becomes 7->6->None
llist.push(7);
# Insert 1 at the beginning. So linked list becomes 1->7->6->None
llist.push(1);
# Insert 4 at the end. So linked list becomes 1->7->6->4->None
llist.append(4)
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
print( "Created linked list is:"),
llist.printList()
32
OUTPUT
33
RESULT
The above program is executed and hence captured the necessary output.
PROGRAM .NO: 8 DATE:
COMMAND LINE ARGUMENT (WORD COUNT)
AIM
To Write a program that takes Command Line Argument (Word count)
ALGORITHM
Step 1: Start the Program.
Step 2: Import Sys to access the interpreted variables.
Step 3: Initialize Variable as Fname and pass the argument
fname = sys.argv[0]
lines = 0
words = 0
letters = 0
34
Step 4: End the program.
SOURCE CODE
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 12:50:34 2021
@author: Mercy Deepa
"""
import sys
fname = sys.argv[0]
lines = 0
words = 0
letters = 0
for line in open(fname):
lines += 1
letters += len(line)
pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'
35
print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)
OUTPUT
36
RESULT
The above program is executed and hence captured the necessary output.
PROGRAM .NO: 9 DATE:
DELETION OPERATION USING SINGLY LINKED LIST
AIM
To Perform deletion operation using Singly Linked List
ALGORITHM
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD -> NEXT
Step 4: FREE PTR
Step 5: EXIT
37
SOURCE CODE
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
38
new_node.next = self.head
self.head = new_node
# Given a reference to the head of a list and a key,
# delete the first occurrence of key in linked list
def deleteNode(self, key):
# Store head node
temp = self.head
# If head node itself holds the key to be deleted
if (temp is not None):
if (temp.data == key):
self.head = temp.next
temp = None
return
# Search for the key to be deleted, keep track of the
# previous node as we need to change 'prev.next'
while(temp is not None):
if temp.data == key:
break
prev = temp
temp = temp.next
39
# if key was not present in linked list
if(temp == None):
return
# Unlink the node from linked list
prev.next = temp.next
temp = None
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print (" %d" %(temp.data)),
temp = temp.next
# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
print ("Created Linked List: ")
llist.printList()
llist.deleteNode(1)
print ("\nLinked List after Deletion of 1:")
40
llist.printList()
OUTPUT
41
RESULT
The above program is executed and hence captured the necessary output.
PROGRAM .NO: 10 DATE:
LINE CHART IN MS EXCEL SHEET
AIM
To Write a Python program to plot the Line chart in MS Excel Sheet using
XlsxWriter module to display the annual net income of the companies
mentioned below
YEAR COMPANY PROFIT
2010 Microsoft 18.76
2011 Microsoft 23.15
2012 Microsoft 16.98
2013 Microsoft 21.86
2014 Microsoft 22.07
2015 Microsoft 12.19
2016 Microsoft 16.8
2017 Microsoft 21.2
2010 Alphabet 8.372
2011 Alphabet 9.706
2012 Alphabet 10.179
2013 Alphabet 12.733
2014 Alphabet 14.136
2015 Alphabet 16.348
2016 Alphabet 19.478
2017 Alphabet 12.662
2010 Amazon 1.152
2011 Amazon 0.631
2012 Amazon 0.139
2013 Amazon 0.274
2014 Amazon 0.241
2015 Amazon 0.596
2016 Amazon 2.371
2017 Amazon 3.033
ALGORITHM
Step 1: Start the Program.
42
Step 2: import XLWRITTER and add the name of the workbook as:
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
Step 3: Mention the headings as Year, Company, Profit.
Step 4: Provide the Given Information as input in DATA.
Step 5: Initialize Array for the Worksheet column A2,B2,C2.
Step 6: Add workbook and Series to the chart as:
chart1 = workbook.add_chart({'type': 'line'})
chart1.add_series({
'name': ' = Sheet1 !$B$1',
'categories': ' = Sheet1 !$A$2:$A$25',
'values': ' = Sheet1 !$B$2:$B$25',
})
chart1.add_series({
'name': ['Sheet1', 0, 2],
'categories': ['Sheet1', 1, 0, 6, 0],
'values': ['Sheet1', 1, 2, 6, 2],
})
Step 7: Set X-axis and Y-axis to Display the line Graph in Chart.
Step 8: End the program.
43
SOURCE CODE
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 12:50:34 2021
@author: Mercy Deepa
"""
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold':1})
headings = ['Year', 'Company', 'Profit']
data = [
[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2010, 2011, 2012, 2013,
2014, 2015, 2016, 2017, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
['Microsoft', 'Microsoft', 'Microsoft', 'Microsoft', 'Microsoft', 'Microsoft',
'Microsoft', 'Microsoft', 'Alphabet', 'Alphabet', 'Alphabet', 'Alphabet',
'Alphabet', 'Alphabet', 'Alphabet', 'Alphabet', 'Amazon', 'Amazon', 'Amazon',
'Amazon', 'Amazon', 'Amazon', 'Amazon', 'Amazon'],
[18.76, 23.15, 16.98, 21.86, 22.07, 12.19, 16.8, 21.2, 8.372, 9.706, 10.179,
12.733, 14.136, 16.348, 19.478, 12.662, 1.152, 0.631, 0.139, 0.274, 0.241,
0.596, 2.371, 3.033]
]
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
44
chart1 = workbook.add_chart({'type': 'line'})
chart1.add_series({
'name': ' = Sheet1 !$B$1',
'categories': ' = Sheet1 !$A$2:$A$25',
'values': ' = Sheet1 !$B$2:$B$25',
})
chart1.add_series({
'name': ['Sheet1', 0, 2],
'categories': ['Sheet1', 1, 0, 6, 0],
'values': ['Sheet1', 1, 2, 6, 2],
})
chart1.set_title({'name': 'Annual Net Income Of The Companies'})
chart1.set_x_axis({'name': 'Year'})
chart1.set_y_axis({'name': 'Profit'})
chart1.set_style(11)
worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10})
workbook.close()
45
OUTPUT
46
RESULT
The above program is executed and hence captured the necessary output.
47