Professional Documents
Culture Documents
BHUVAN PYTHON PROJ
BHUVAN PYTHON PROJ
Section CSE-DS
Batch (D1/D2) D1
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
2
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
INDEX
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).
3
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
8
To write a python program selection sort. To
write a python program Insertion sort
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
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]
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:
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
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:
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):
def isEmpty(self):
return len(self.queue) == 0
self.queue.append(data)
def delete(self):
try:
max_val = 0
for i in range(len(self.queue)):
max_val = i
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)
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:
26
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
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
if divisor == 0:
try:
print("Result:", result)
except CustomException as e:
print("Error:", e)
except ValueError:
except Exception as e:
print("Error:", e)
31
BHUVAN SHRIVASTAV (2100971540020)
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
Output :
32
BHUVAN SHRIVASTAV (2100971540020)