0% found this document useful (0 votes)
40 views32 pages

Bhuvan Python Proj

Uploaded by

jay007godspeed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views32 pages

Bhuvan Python Proj

Uploaded by

jay007godspeed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Galgotias College of Engineering & Technology

Affiliated to Dr. A.P.J. Abdul Kalam Technical University, Lucknow

Department of Computer Science & Engineering

Python Language Programming Lab (KCS-453)


SESSION: 2022-23

Name BHUVAN SHRIVASTAV

Roll no. 2100971540020

Section CSE-DS

Batch (D1/D2) D1
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

2
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

INDEX

S PROGRAMS DATE SIGN


No
.

1
To write a python program that takes in
command line arguments as input (two
numbers), it print the number of arguments and
sum of the input arguments.
Write a program to check for Armstrong Number.

2
To write a python program to perform matrix
multiplication.

3
To write a python program to compute the GCD
of two numbers
To write a python program to find the most
frequent words in a text file (ignore punctuations).

4
To write a python program find the square root of
a number (Newton’s method).

5
To write a python program exponentiation
(power of a number).

6 To write a python program find the maximum of


a list of numbers.
To write a python program that prints first n
prime numbers.

7 To write a python program linear search.


To write a python program Binary search

3
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

8
To write a python program selection sort. To
write a python program Insertion sort

9 To write a python program merge sort.

10 Implement stack using list data structure & OOP


and methods pop, push, isEmpty, isFull,
displayStack.
Write a program to handle User-defined
Exceptions in Python

11
Implement Queue using list data structure
&OOP and methods enqueue, dequeue, isFull,
isEmpty, display

12
Implement Priority Queue using list data
structure &OOP and methods enqueuer,
dequeue, isFull, display

13
Implement Heap (maxheap) using list data
structure & OOP and methods add and remove
elements from maxheap

14
Implement Linked List using OOP with methods
insert_head, insert_tail, delete_head,
delete_tail, delete_by_value and Print_LList.

4
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 1
Aim: To write a Python program that takes in command line arguments as
input, it prints the number of arguments and the sum of the input arguments.

Code:
#Bhuvan Vinayak
import sys
print("number of arguments",len(sys.argv))
sum=0 for i in range(1,len(sys.argv)):
sum += int(sys.argv[i]) print("sum of
numbers:",sum)

Output:

PROGRAM 2

5
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Aim: Write a program to check for Armstrong’s number.

Code:
#Bhuvan Vinayak
import sys num =
int(sys.argv[1])
order=len(str(num))
sum = 0 temp
= num while
(temp>0):
digit=temp%10
sum = sum + digit ** order
temp = temp//10 if
(num==sum): print(f"{num}
is armstrong") else:
print(f"{num} is not armstrong")

Output:

PROGRAM 3
Aim:To write a python program to perform matrix multiplication.
6
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Code:
#Bhuvan Vinayak
matrix_A_rows = int(input('Enter number of rows for matrix-A: '))
matrix_A_cols = int(input('Enter number of columns for matrix-A:
matrix_B_rows = int(input('Enter number of rows for matrix-B: '))
matrix_B_cols = int(input('Enter number of columns for matrix-B: '))
if matrix_A_cols == matrix_B_rows:
print('Enter values for matrix A')
matrix_A = [[int(input(f"column {j+1} -> ENter {i+1} element:")) for j in
range(matrix_A_cols)] for i in range(matrix_A_rows) ] print('Enter
values for matrix B ')
matrix_B = [[int(input(f"column {j+1} -> ENter {i+1} element:")) for j in
range(matrix_B_cols)] for i in range(matrix_B_rows) ] print('Matrix-A
:') for i in matrix_A: print(i) print('Matrix-B :') for i in
matrix_B: print(i) result = [[0 for j in range(matrix_B_cols)] for i
in range(matrix_A_rows)] for i in range(len(matrix_A)):
for j in range(len(matrix_B[0])):
for k in range(len(matrix_B)):
result[i][j] += matrix_A[i][k] * matrix_B[k][j]
print('Multiplication of Matrix-A and Matrix-B is :')
for i in result:
print(i) else:
print('Multiplication of matrices is not possible (columns of matrix-A =
row of matrix-B)')

Output:

7
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

8
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 4
Aim: Write a program to find the GCD of two numbers.

Code:
#Bhuvan Vinayak
num1 = int(input("Enter the first number="))
num2 = int(input("Enter the second number="))
if(num1!=num2): if(num1>num2):
x=num1 y=num2
else:
x=num2
y=num1
while(y!=0):
t=y y=x%y
x=t
print(f"HCF of {num1} and {num2} is:",x) else:
print(f"HCF of {num1} and {num2} is:",num1)

Output:

9
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 5
Aim:To write a python program to find the most frequent words in a text file
(ignore punctuations).

Code:
#Bhuvan Vinayak
file = open("anubhav.txt","r")
frequent_word = " "
frequency = 0 words = [] for
line in file:
line_word = line.lower().replace(',','').replace('.','').split(" ");
for w in line_word:
words.append(w)
for i in range(0, len(words)):
count = 1; for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1
if(count > frequency):
frequency = count
frequent_word = words[i]
print("Most repeated word : " + frequent_word)
print("Frequency of the most frequent word : " + str(frequency))
file.close()

File:

Output:

10
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 6
Aim:To write a python program find the square root of a number (Newton’s
method).

Code:
#Bhuvan Vinayak
def newton(n,iter):
approx=0.5*n for i
in range(iter):
betterapprox=0.5*(approx+(n/approx))
approx=betterapprox return approx n=int(input("Enter the
number=")) iter=int(input("Enter the number of iteration="))
print("Square root of the given number=",newton(n,iter))

Output:

11
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 7
Aim:To write a python program exponentiation (power of a number).

Code:
#Bhuvan Vinayak
def exponent(base,power):
if(power==1): return base
else: return(base*exponent(base,power-1))
base=int(input("Enter the number="))
power=int(input("Enter the exponent="))
print(base,"^",power,"=",exponent(base,power))

Output:

12
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 8
Aim:To write a python program that prints first n prime numbers.

Code:
#Bhuvan Vinayak
n=int(input("Enter number of element in
list")) mylist=[] print("Enter elements of the
list") for _ in range(n): a=int(input())
mylist.append(a) maximum=mylist[0] for i in
mylist: if maximum<i: maximum=i
print("Maximum of the list is :",maximum)

Output:

13
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 9
Aim:To write a python program that prints first n prime numbers.

Code:
#Bhuvan Vinayak
n=int(input("Enter the number till where prime to be
print:")) def prime(n): prime=[] for i in range(0,n+1):
flag=0
if(i<2):
continue
if(i==2):

prime.append(2)
for x in range(2,i):
if(i%x==0):
flag=1 break
if(flag==0):
prime.append(i)
return prime
print("Prime nubers : ",prime(n))
Output:

14
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 10
Aim:To write a python of Linear Search.

Code:
#Bhuvan Vinayak
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not
present.""" for i in range(len(alist)): if
alist[i] == key: return i return -1
alist = input('Enter the list of numbers: ')
alist = alist.split() alist =
[int(x) for x in alist]
key = int(input('The number to search for: '))
index = linear_search(alist, key) if index < 0:
print('{} was not found.'.format(key)) else:
print('{} was found at index {}.'.format(key, index))

Output:

15
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 11
Aim:To write a python program of Binary Search.

Code:
#Bhuvan Vinayak def
binary_search(alist, key):
"""Search key in alist[start... end -
1].""" start = 0 end =
len(alist) while start < end:
mid = (start + end)//2 if alist[mid] >
key: end = mid
elif alist[mid] < key: start =
mid + 1 else:
return mid return -1
alist = input('Enter the sorted list of numbers:
') alist = alist.split() alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = binary_search(alist, key) if index < 0:
print('{} was not found.'.format(key)) else:
print('{} was found at index {}.'.format(key, index))

Output:

16
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 12
Aim:To write a python of Selection Sort.

Code:
#Bhuvan Vinayak
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i for j in
range(i + 1, len(alist)): if
alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

Output:

17
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 13
Aim:To write a python of Insertion Sort.

Code:
#Bhuvan Vinayak
def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i] j=i-1 while (j
>= 0 and temp < alist[j]):
alist[j + 1] = alist[j] j=j-
1
alist[j + 1] = temp
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)

Output:

18
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 14
Aim:To write a python of Merge Sort.

Code:

def merge_sort(alist, start, end):


'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end) def merge_list(alist,
start, mid, end): left = alist[start:mid]
right = alist[mid:end] k = start
i=0 j=0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]): alist[k] =
left[i] i=i+1 else:
alist[k] = right[j]
j=j+1 k=k+
1 if start + i < mid:
while k < end:
alist[k] = left[i]
i=i+1
k=k+1 else:
while k < end:
alist[k] = right[j]
j=j+1 k=k+
1
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
Output:

19
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 15
Aim: Implement stack using list data structure & OOP and methods pop,
push, isEmpty, isFull, displayStack.

Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack: def
__init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node
print(f"Pushed element: {data}")
def pop(self): if self.is_empty():
print("Stack is empty. Cannot perform pop operation.")
return None
popped_element = self.top.data
self.top = self.top.next
print(f"Popped element: {popped_element}")
return popped_element def display(self):
if self.is_empty():
print("Stack is empty.")
return current =
self.top print("Stack
elements:") while current
is not None:
print(current.data)
current = current.next
stack = Stack() while
True:
print("\nSTACK OPERATIONS")
print("1. Push")
print("2. Pop") print("3.
Display") choice =
input("Enter your choice
(1-4): ") if choice == '1':

20
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

element = input("Enter the element to push: ")


stack.push(element) elif choice == '2':
popped = stack.pop() if
popped is not None:
print("Popped element:", popped) elif
choice == '3': stack.display()
else:
print("Invalid choice. Please enter a valid option.")
Output:

21
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 17
Aim: Implement Queue using list data structure & OOPs and methods
enqueue, dequeue, isFull, isEmpty, display.

Code:

class Queue: def


__init__(self):
self.q=[] def
enqueue(self,item):
self.q.append(item)
def dequeue(self): if
len(self.q)<1:
return None return
self.q.pop(0) def
display (self):
print(self.q) def
isEmpty(self): return
self.item==[] def
size(self):
return len(self.q)
rq=Queue()
print("\nQUEUE OPERATIONS")
print("1. Enqueue") print("2.
Dequeue") print("3. Display")
print("4. Size") print("5. Exit")
while True:
choice=input("Enter the choice(1-4)=")
if choice=='1':
element=input("Enter the element to
enqueue=") rq.enqueue(element) elif
choice=='2': d=rq.dequeue() if d is not
None:
print("Dequeued element:",d)
else:
print("Cannot be dequeued")

22
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

elif choice=='3':
print(rq.display()) elif choice=='4':
print("Size of queue : ",rq.size())

Output:

23
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 18
Aim:

Implement Priority Queue using list data structure &OOP and methods enqueuer, dequeue,
isFull, display.

Code:

class PriorityQueue(object):

def __init__(self):

self.queue = []

def __str__(self):

return ' '.join([str(i) for i in self.queue])

def isEmpty(self):
return len(self.queue) == 0

def insert(self, data):

self.queue.append(data)

def delete(self):

try:

max_val = 0
for i in range(len(self.queue)):

if self.queue[i] > self.queue[max_val]:

max_val = i

item = self.queue[max_val] del self.queue[max_val]

return item

except IndexError:

print()
24
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

exit()

if __name__ == '__main__':

myQueue = PriorityQueue()

myQueue.insert(12)

myQueue.insert(1)

myQueue.insert(14)

myQueue.insert(7)

print(myQueue)

while not myQueue.isEmpty():

print(myQueue.delete())

Output:

25
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 19
Aim: Implement Heap (maxheap) using list data structure & OOP and
methods add and remove elements from maxheap

Code:

class MaxHeap: def


__init__(self):
self.heap = [] def
insert(self, value):
self.heap.append(value)
self._sift_up(len(self.heap) - 1) def
delete(self, value):
if value not in self.heap:
raise ValueError("Value not found in the heap")
index = self.heap.index(value) if index ==
len(self.heap) - 1: self.heap.pop() else:
self.heap[index] = self.heap.pop() self._sift_down(index)
def _sift_up(self, index): parent_index = (index - 1) // 2 if
parent_index >= 0 and self.heap[index] > self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index],
self.heap[index] self._sift_up(parent_index) def _sift_down(self,
index):
left_child_index = 2 * index + 1 right_child_index =
2 * index + 2 largest = index if (left_child_index <
len(self.heap) and self.heap[left_child_index] >
self.heap[largest]): largest = left_child_index if
(right_child_index < len(self.heap) and
self.heap[right_child_index] > self.heap[largest]):
largest = right_child_index if largest != index:
self.heap[index], self.heap[largest] = self.heap[largest],
self.heap[index]
self._sift_down(largest) print("1.
Insert value")
print("2. Delete value")
print("3. Print heap") print("4.
Exit")
heap = MaxHeap() while True: choice =
int(input("Enter your choice: ") if choice ==
1: value = int(input("Enter value to insert:

26
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

")) heap.insert(value) print("Value


inserted successfully.") elif choice == 2:
value = int(input("Enter value to delete: "))
try:
heap.delete(value)
print("Value deleted successfully.")
except ValueError as e: print(e)
elif choice == 3:
print("Heap:", heap.heap)
elif choice == 4:
break
else:
print("Invalid choice. Please try again.")

Output:

27
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 20
Aim: Implement Linked List using OOP with methods insert_head,
insert_tail, delete_head, delete_tail, delete_by_value and Print_LList

Code:
class Node: def
__init__(self, data):
self.data = data
self.next = None class
LinkedList: def __init__(self):
self.head = None def
insert_head(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node def
insert_tail(self, data):
new_node = Node(data) if
self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node def
delete_head(self): if
self.head is None:
return self.head =
self.head.next def
delete_tail(self): if
self.head is None:
return if
self.head.next is None:
self.head = None
return current =
self.head while
current.next.next:
current = current.next
current.next = None
def delete_by_value(self, value):
if self.head is None:

28
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

return if
self.head.data == value:
self.head = self.head.next
return current =
self.head while current.next:
if current.next.data == value:
current.next = current.next.next
return current =
current.next def print_llist(self):
if self.head is None:
print("Linked List is empty.")
return current =
self.head while current:
print(current.data, end=" ")
current = current.next print()
print("\nLinked List Operations:")
print("1. Insert at Head")
print("2. Insert at Tail") print("3.
Delete Head") print("4. Delete
Tail") print("5. Delete by Value")
print("6. Print Linked List")
print("7. Exit") llist = LinkedList()
while True:
choice = int(input("Enter your choice: ")) if choice == 1:
value = int(input("Enter the value to insert at the head: "))
llist.insert_head(value) print("Value inserted at the
head.") elif choice == 2: value = int(input("Enter the
value to insert at the tail: ")) llist.insert_tail(value)
print("Value inserted at the tail.") elif choice == 3:
llist.delete_head() print("Head node deleted.") elif
choice == 4:
llist.delete_tail() print("Tail node deleted.")
elif choice == 5: value = int(input("Enter the
value to delete: ")) llist.delete_by_value(value)
print("Node with value {} deleted.".format(value))
elif choice == 6: print("Linked List:")
llist.print_llist() elif choice == 7: break else:
print("Invalid choice. Please try again.")

29
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Output

30
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

PROGRAM 16
Aim: Write a program to handle User-defined Exceptions in Python

Code:

class CustomException(Exception):

pass

def divide_numbers(dividend, divisor):

if divisor == 0:

raise CustomException("Cannot divide by zero")

return dividend / divisor

try:

dividend = int(input("Enter the dividend: "))

divisor = int(input("Enter the divisor: "))

result = divide_numbers(dividend, divisor)

print("Result:", result)

except CustomException as e:

print("Error:", e)

except ValueError:

print("Error: Invalid input. Please enter integer values.")

except Exception as e:

print("Error:", e)

31
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Output :

32
BHUVAN SHRIVASTAV (2100971540020)

You might also like