0% found this document useful (0 votes)
7 views52 pages

Python Sparse Matrix and Linked List Operations

Uploaded by

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

Python Sparse Matrix and Linked List Operations

Uploaded by

lolagepranav84
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Student Name: Class:

Program Title: Date:

Remark:

Q1. Write a python program for to implement the sparse


matrix.

r=int(input("Enter the number of rows:"))


c=int(input("Enter the number of columns:"))
m=[]
print("Enter the first matrix:")
for i in range(r):
l=[]
for j in range(c):
num=int(input("Enter the element:"))
[Link](num)
[Link](l)

print("Display the matrix:")


for i in m:
print(i,end="\n")

r1=[]
c1=[]
val=[]
for i in range(r):
for j in range(c):
if m[i][j]!=0:
[Link](i)
[Link](j)
[Link](m[i][j])

print("Saprse matrix:")
print("Rows=",r1)
print("columns=",c1)
print("value=",val)
Output:

Enter the number of rows:3


Enter the number of columns:3
Enter the first matrix:
Enter the element:10
Enter the element:0
Enter the element:0
Enter the element:0
Enter the element:20
Enter the element:0
Enter the element:0
Enter the element:0
Enter the element:0
Display the matrix:
[10, 0, 0]
[0, 20, 0]
[0, 0, 0]
Saprse matrix:
Rows= [0, 1]
columns= [0, 1]
value= [10, 20]
Student Name: Class:

Program Title: Date:

Remark:

Q2. Write a python program to find the addition of sparse


matrix element.

r=int(input("Enter the number of rows:"))


c=int(input("Enter the number of columns:"))
m=[]
print("Enter the first matrix:")
for i in range(r):
l=[]
for j in range(c):
num=int(input("Enter the element:"))
[Link](num)
[Link](l)

print("Display the matrix:")


for i in m:
print(i,end="\n")

r1=[]
c1=[]
val=[]
s=0
for i in range(r):
for j in range(c):
if m[i][j]!=0:
[Link](i)
[Link](j)
[Link](m[i][j])
s=s+m[i][j]

print("Saprse matrix:")
print("Rows=",r1)
print("columns=",c1)
print("value=",val)
print("Addition=",s)

Output:
Enter the number of rows:3
Enter the number of columns:3
Enter the first matrix:
Enter the element:1
Enter the element:0
Enter the element:0
Enter the element:4
Enter the element:8
Enter the element:0
Enter the element:0
Enter the element:0
Enter the element:6
Display the matrix:
[1, 0, 0]
[4, 8, 0]
[0, 0, 6]
Saprse matrix:
Rows= [0, 1, 1, 2]
columns= [0, 0, 1, 2]
value= [1, 4, 8, 6]
Addition= 19
Student Name: Class:

Program Title: Date:

Remark:

Q3. Write a python program to implement the following


operation on linked list.
class Node:
def __init__(self,data):
[Link]=data
[Link]=None
class LinkedList:
def __init__(self):
[Link]=None
def Insert_End(self,data):
temp=Node(data)
if [Link] is None:
[Link]=temp
else:
q=[Link]
while [Link]:
q=[Link]
[Link]=temp

def Display(self):
if [Link] is None:
print("Linked List is Empty")
else:
q=[Link]
while q:
print([Link],end="->")
q=[Link]
print("None")

def Sort(self):
if [Link] is None:
print("List is Empty")
return
values=[]
q=[Link]
while q:
[Link]([Link])
q =[Link]
[Link]()
print("Sorted List=",values)

l1=LinkedList()
while True:
print("-----Choises are:----")
print("1.Insert_End")
print("[Link]")
print("[Link] in Acending order")
print("[Link]")
ch=int(input("Enter your choise:"))
if ch==1:
data=int(input("Enter the Element to insert at end:"))
l1.Insert_End(data)
elif ch==2:
[Link]()
elif ch==3:
[Link]()
else:
exit(0)

Output:
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:1
Enter the Element to insert at end:11
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:1
Enter the Element to insert at end:77
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:1
Enter the Element to insert at end:56
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:1
Enter the Element to insert at end:25
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:1
Enter the Element to insert at end:90
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:2
11->77->56->25->90->None
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:3
Sorted List= [11, 25, 56, 77, 90]
-----Choises are:----
1.Insert_End
[Link]
[Link] in Acending order
[Link]
Enter your choise:
Student Name: Class:

Program Title: Date:

Remark:

Q4: Write a python program to create a single linked list of


element of type integer and find the union of them.

class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def Insert_End(self, data):
temp = Node(data)
if [Link] is None:
[Link] = temp
else:
q = [Link]
while [Link]:
q = [Link]
[Link] = temp

def Display(self):
if [Link] is None:
print("Linked List is Empty")
else:
q = [Link]
while q:
print([Link], end="->")
q = [Link]
print("None")

def union(self, other_list):


# Function to find the union of two linked lists (unique
elements from both)
s = set()
q = [Link]
while q:
[Link]([Link])
q = [Link]
q = other_list.head
while q:
[Link]([Link])
q = [Link]
union_list = LinkedList()
for item in s:
union_list.Insert_End(item)
return union_list

# Create two linked lists


l1 = LinkedList()
l2 = LinkedList()

while True:
print("-----Choices are:----")
print("1. Insert into List 1")
print("2. Insert into List 2")
print("3. Display List 1")
print("4. Display List 2")
print("5. Union of List 1 and List 2")
print("0. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
data = int(input("Enter the Element to insert at end of
List 1: "))
l1.Insert_End(data)
elif ch == 2:
data = int(input("Enter the Element to insert at end of
List 2: "))
l2.Insert_End(data)
elif ch == 3:
print("List 1:")
[Link]()
elif ch == 4:
print("List 2:")
[Link]()
elif ch == 5:
union_ll = [Link](l2)
print("Union of List 1 and List 2:")
union_ll.Display()
elif ch == 0:
exit(0)
else:
print("Invalid choice. Please try again.")

Output:
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 1
Enter the Element to insert at end of List 1: 11
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 1
Enter the Element to insert at end of List 1: 55
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 1
Enter the Element to insert at end of List 1: 2
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 1
Enter the Element to insert at end of List 1: 5
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 1
Enter the Element to insert at end of List 1: 77
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 2
Enter the Element to insert at end of List 2: 2
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 2
Enter the Element to insert at end of List 2: 5
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 2
Enter the Element to insert at end of List 2: 1
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 2
Enter the Element to insert at end of List 2: 85
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 2
Enter the Element to insert at end of List 2: 66
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 3
List 1:
11->55->2->5->77->None
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 4
List 2:
2->5->1->85->66->None
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice: 5
Union of List 1 and List 2:
1->2->66->5->11->77->85->55->None
-----Choices are:----
1. Insert into List 1
2. Insert into List 2
3. Display List 1
4. Display List 2
5. Union of List 1 and List 2
0. Exit
Enter your choice:
Student Name: Class:

Program Title: Date:

Remark:

Q5: Write a python program to insert element in a circular


linked list.
[Link] the end of the List
[Link] Between the list.
class Node:
def __init__(self, data):
[Link] = data
[Link] = None

class CircularSinglyLinkedList:
def __init__(self):
[Link] = None

def insert_end(self, data):


new_node = Node(data)
if [Link] is None:
[Link] = new_node
new_node.next = [Link]
else:
temp = [Link]
while [Link] != [Link]:
temp = [Link]
[Link] = new_node
new_node.next = [Link]

def insert_at_position(self, data, position):


if position <= 0:
print("Invalid position. Position must be a positive
integer.")
return
new_node = Node(data)
if [Link] is None:
if position == 1:
[Link] = new_node
new_node.next = [Link]
else:
print("List is empty. Can only insert at position 1.")
return
if position == 1:
new_node.next = [Link]
temp = [Link]
while [Link] != [Link]:
temp = [Link]
[Link] = new_node
[Link] = new_node
return
temp = [Link]
count = 1
while count < position - 1 and [Link] != [Link]:
temp = [Link]
count += 1
if count < position - 1:
print(f"Position {position} is beyond the list length.
Inserting at the end.")
new_node.next = [Link]
[Link] = new_node
return
new_node.next = [Link]
[Link] = new_node

def display(self):
if [Link] is None:
print("List is empty")
return
temp = [Link]
while True:
print([Link], end=" -> ")
temp = [Link]
if temp == [Link]:
break
print("(head)")
cll = CircularSinglyLinkedList()

while True:
print("\[Link] at End\[Link] Between \[Link]\
[Link]")
ch = int(input("Enter choice: "))

if ch == 1:
d = int(input("Enter data: "))
cll.insert_end(d)
elif ch == 2:
d = int(input("Enter data: "))
pos = int(input("Enter position: "))
cll.insert_at_position(d, pos)
elif ch == 3:
[Link]()
elif ch == 0:
exit(0)
else:
print("Invalid choice")

Output:
[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 1
Enter data: 11

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 1
Enter data: 21

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 1
Enter data: 45

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 1
Enter data: 67

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 1
Enter data: 55

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 3
11 -> 21 -> 45 -> 67 -> 55 -> (head)

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 2
Enter data: 90
Enter position: 3

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice: 3
11 -> 21 -> 90 -> 45 -> 67 -> 55 -> (head)

[Link] at End
[Link] Between
[Link]
[Link]
Enter choice:
Student Name: Class:

Program Title: Date:

Remark:

Q6 Write a python program to print singly Linked List in


Reverse.

class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def insert_end(self, data):
temp = Node(data)
if [Link] is None:
[Link] = temp
else:
q = [Link]
while [Link]:
q = [Link]
[Link] = temp
def reverse(self):
prev = None
q = [Link]
while q:
nxt = [Link]
[Link] = prev
prev = q
q = nxt
[Link] = prev
def display(self):
q = [Link]
if q is None:
print("List is empty")
return
while q!=None:
print([Link], end="->")
q = [Link]
print("None")

ll = LinkedList()
while True:
print("\n--- Singly Linked List Menu ---")
print("1. Insert at End")
print("2. Reverse List")
print("3. Display List")
print("0. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
data = int(input("Enter value to insert at end: "))
ll.insert_end(data)
elif choice == 2:
[Link]()
print("List reversed.")
elif choice == 3:
[Link]()
elif choice == 0:
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

Output:

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 1
Enter value to insert at end: 7

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 1
Enter value to insert at end: 2

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 1
Enter value to insert at end: 9

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 1
Enter value to insert at end: 11

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 3
7->2->9->11->None

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 2
List reversed.

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice: 3
11->9->2->7->None

--- Singly Linked List Menu ---


1. Insert at End
2. Reverse List
3. Display List
0. Exit
Enter your choice:

Student Name: Class:


Program Title: Date:

Remark:

Q7. Write a python program to Accept Number from user &


create linked list of digits of that number
Eg: N=12845
Linked List-1→2→3→4→5.

class Node:
def __init__(self, data):
[Link] = data
[Link] = None

class LinkedList:
def __init__(self):
[Link] = None

def append(self, data):


if not [Link]:
[Link] = Node(data)
else:
current = [Link]
while [Link]:
current = [Link]
[Link] = Node(data)

def display(self):
current = [Link]
while current:
print([Link], end="→" if [Link] else "\n")
current = [Link]

# Get user input and create linked list


num = input("Enter a number: ")
ll = LinkedList()
for digit in num:
if [Link]():
[Link](int(digit))

print("Linked List:")
[Link]()

Output:
Enter a number: 1234
Linked List:
1→2→3→4
Student Name: Class:

Program Title: Date:

Remark:

Q8 Write a Python programs to implement dynamic Queue.

queue = []
front = -1
rear = -1

def enqueue():
global front, rear
element = input("Enter element to add: ")
[Link](element)
if front == -1:
front = 0
rear += 1
print(f"{element} added to the queue at position {rear}.")

def dequeue():
global front, rear
if front == -1 or front > rear:
print("Queue Underflow! Queue is empty.")
else:
element = queue[front]
print(f"Removed element: {element}")
front += 1
if front > rear:
front = rear = -1
[Link]()

def peek():
if front == -1:
print("Queue is empty!")
else:
print(f"Front element is: {queue[front]}")
def display():
if front == -1:
print("Queue is empty!")
else:
print(f"Front index = {front}, Rear index = {rear}")
print("Current Queue:", queue[front:rear+1])

while True:
print("\n--- Dynamic Queue (with Front & Rear) ---")
print("1. Enqueue (Add)")
print("2. Dequeue (Remove)")
print("3. Peek (Front Element)")
print("4. Display Queue")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
enqueue()
elif choice == '2':
dequeue()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting... Thank you!")
break
else:
print("Invalid choice! Please enter between 1 to 5.")

Output:

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 1
Enter element to add: 1
1 added to the queue at position 0.

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 1
Enter element to add: 2
2 added to the queue at position 1.

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 1
Enter element to add: 3
3 added to the queue at position 2.

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 4
Front index = 0, Rear index = 2
Current Queue: ['1', '2', '3']

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 2
Removed element: 1

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 4
Front index = 1, Rear index = 2
Current Queue: ['2', '3']

--- Dynamic Queue (with Front & Rear) ---


1. Enqueue (Add)
2. Dequeue (Remove)
3. Peek (Front Element)
4. Display Queue
5. Exit
Enter your choice (1-5): 3
Front element is: 2

Student Name: Class:


Program Title: Date:

Remark:

Q9. Write a python program to reverse a string using stack.

class Stack:
def __init__(self):
[Link] = []

def push(self, char):


[Link](char)

def pop(self):
if not self.is_empty():
return [Link]()
return None

def is_empty(self):
return len([Link]) == 0

def reverse_string(s):
stack = Stack()
for char in s:
[Link](char)
reversed_s = ""
while not stack.is_empty():
reversed_s += [Link]()
return reversed_s

# Get user input


string = input("Enter a string: ")
print(f"Original String: {string}")
print(f"Reversed String: {reverse_string(string)}")
Output:
Enter a string: aditya
Original String: aditya
Reversed String: aytida
Student Name: Class:

Program Title: Date:

Remark:
Student Name: Class:

Program Title: Date:

Remark:

write a python program to create binary search tree &


traverse it by using in-order and post-order
# Node class
class Node:
Output: def __init__(self, key):
Enter elements to insert
into BST (space- [Link] = key
separated):
25 75 86 94 52 36 85
[Link] = None
[Link] = None
In-order Traversal:
25 36 52 75 85 86 94
Post-order Traversal:
36 52 85 94 86 75 25
# Binary Search Tree class
class BST:
def __init__(self):
[Link] = None

# Insert a node into BST


def insert(self, root, key):
if root is None:
return Node(key)
if key < [Link]:
[Link] = [Link]([Link], key)
else:
[Link] = [Link]([Link], key)
return root

# In-order Traversal (Left → Root → Right)


def inorder(self, root):
if root:
[Link]([Link])
print([Link], end=" ")
[Link]([Link])

# Post-order Traversal (Left → Right → Root)


def postorder(self, root):
if root:
[Link]([Link])
[Link]([Link])
print([Link], end=" ")

# -------- Main Program --------


tree = BST()
root = None

print("Enter elements to insert into BST (space-separated):")


elements = list(map(int, input().split()))

for elem in elements:


root = [Link](root, elem)

print("\nIn-order Traversal:")
[Link](root)

print("\nPost-order Traversal:")
[Link](root)

Student Name: Class:

Program Title: Date:

Remark:

write a python program to create BST & print its mirror tree

# Node class
class Node:
def __init__(self, key):
Output: [Link] = key
Enter values to insert into
BST (space-separated):
[Link] = None
45 65 87 98 28 52 63 [Link] = None
In-order Traversal of
Original BST:
28 45 52 63 65 87 98
# Binary Search Tree class
In-order Traversal of
Mirror BST: class BST:
98 87 65 63 52 45 28 def __init__(self):
[Link] = None

# Insert a node in BST


def insert(self, root, key):
if root is None:
return Node(key)
if key < [Link]:
[Link] = [Link]([Link], key)
else:
[Link] = [Link]([Link], key)
return root

# Inorder Traversal (Left → Root → Right)


def inorder(self, root):
if root:
[Link]([Link])
print([Link], end=" ")
[Link]([Link])

# Mirror of Tree (swap left and right)


def mirror(self, root):
if root:
[Link], [Link] = [Link], [Link]
[Link]([Link])
[Link]([Link])
return root

# ----------------------- MAIN PROGRAM -----------------------


tree = BST()
root = None

# Input elements
print("Enter values to insert into BST (space-separated):")
elements = list(map(int, input().split()))

# Insert into BST


for val in elements:
root = [Link](root, val)

# Print original tree


print("\nIn-order Traversal of Original BST:")
[Link](root)

# Mirror the tree


[Link](root)

# Print mirrored tree


print("\n\nIn-order Traversal of Mirror BST:")
[Link](root)
print()
Student Name: Class:

Program Title: Date:

Remark:

write a python program for the following operation on


tree-
1. Create Binary Search Tree
2. Create Mirror of Tree
3. Print Only Leaf Nodes
4. In-Order Traversal
# Node class
class Node:
def __init__(self, key):
Output: [Link] = key
Enter values to insert into [Link] = None
BST (space separated):
65 85 96 47 52 31 20
[Link] = None
In-order Traversal of
Original Tree:
20 31 47 52 65 85 96 # Binary Search Tree class
Leaf Nodes of the Tree: class BST:
20 52 96
def __init__(self):
In-order Traversal of
Mirrored Tree:
[Link] = None
96 85 65 52 47 31 20
# Insert node
def insert(self, root, key):
if root is None:
return Node(key)
if key < [Link]:
[Link] = [Link]([Link], key)
else:
[Link] = [Link]([Link], key)
return root

# In-order traversal (Left → Root → Right)


def inorder(self, root):
if root:
[Link]([Link])
print([Link], end=" ")
[Link]([Link])

# Print leaf nodes only


def printLeafNodes(self, root):
if root:
# If node has no children → leaf node
if [Link] is None and [Link] is None:
print([Link], end=" ")
[Link]([Link])
[Link]([Link])

# Mirror of tree
def mirror(self, root):
if root:
[Link], [Link] = [Link], [Link]
[Link]([Link])
[Link]([Link])
return root

# -----------------------------------------
# MAIN PROGRAM
# -----------------------------------------

tree = BST()
root = None

# Input elements
print("Enter values to insert into BST (space separated):")
values = list(map(int, input().split()))

# Insert elements
for v in values:
root = [Link](root, v)

# In-order traversal
print("\nIn-order Traversal of Original Tree:")
[Link](root)
# Print leaf nodes
print("\n\nLeaf Nodes of the Tree:")
[Link](root)

# Mirror of tree
[Link](root)

# Print mirrored tree (in-order)


print("\n\nIn-order Traversal of Mirrored Tree:")
[Link](root)

print()

Student Name: Class:

Program Title: Date:

Remark:

Python Program to Convert Infix Expression to Postfix

def precedence(op):
if op in ('+', '-'): return 1
if op in ('*', '/'): return 2
Output: if op == '^': return 3
Enter infix return 0
expression:
A+B(C*D)E/F
Postfix expression: def infix_to_postfix(exp):
ABCD*EF/+ stack = []
output = ""

for ch in exp:
if [Link]():
output += ch
elif ch == '(':
[Link](ch)
elif ch == ')':
while stack and stack[-1] != '(':
output += [Link]()
[Link]()
else:
while stack and precedence(ch) <= precedence(stack[-
1]):
output += [Link]()
[Link](ch)

while stack:
output += [Link]()

return output

exp = input("Enter infix expression: ")


print("Postfix expression:", infix_to_postfix(exp))
Student Name: Class:

Program Title: Date:

Remark:

Python Program to Read Adjacency Matrix and Convert


It into Adjacency List

n = int(input("Enter number of vertices: "))

print("Enter adjacency matrix:")


Output: matrix = []
Enter number of for i in range(n):
vertices: 4
Enter adjacency matrix: row = list(map(int, input().split()))
1001 [Link](row)
0110
1010
0101 adj_list = {i: [] for i in range(n)}
Adjacency List:
0 : [0, 3]
1 : [1, 2] for i in range(n):
2 : [0, 2]
3 : [1, 3] for j in range(n):
if matrix[i][j] == 1:
adj_list[i].append(j)

print("Adjacency List:")
for key in adj_list:
print(key, ":", adj_list[key])
Student Name: Class:

Program Title: Date:

Remark:

Python Program to Create Graph & Traverse Using DFS


and BFS

from collections import defaultdict, deque

class Graph:
Output: def __init__(self):
Enter number of edges: [Link] = defaultdict(list)
5
Enter edges (u v):
AB def add_edge(self, u, v):
AC
BD [Link][u].append(v)
CE
DF
Enter starting vertex: A def dfs(self, start, visited=None):
DFS: A B D F C E if visited is None:
BFS: A B C D E F
visited = set()
[Link](start)
print(start, end=" ")
for node in [Link][start]:
if node not in visited:
[Link](node, visited)

def bfs(self, start):


visited = set()
queue = deque([start])
[Link](start)

while queue:
node = [Link]()
print(node, end=" ")
for adj in [Link][node]:
if adj not in visited:
[Link](adj)
[Link](adj)
g = Graph()
n = int(input("Enter number of edges: "))

print("Enter edges (u v):")


for _ in range(n):
u, v = input().split()
g.add_edge(u, v)

start = input("Enter starting vertex: ")

print("DFS:", end=" ")


[Link](start)
print()

print("BFS:", end=" ")


[Link](start)
print()

Student Name: Class:


Program Title: Date:

Remark:

Python Program to Implement Binary Search

def binary_search(arr, x):


low, high = 0, len(arr) - 1

Output: while low <= high:


Enter sorted elements: 70
25 65 48 96 35 20
mid = (low + high) // 2
Enter element to search: if arr[mid] == x:
25
Element found at index 1 return mid
elif x < arr[mid]:
high = mid - 1
else:
Enter sorted elements: low = mid + 1
70 25 65 48 96 35 20
Enter element to return -1
search: 90
Element not found
arr = list(map(int, input("Enter sorted elements: ").split()))
x = int(input("Enter element to search: "))

pos = binary_search(arr, x)

if pos != -1:
print("Element found at index", pos)
else:
print("Element not found")

Student Name: Class:

Program Title: Date:

Remark:
Python Program to Implement Bubble Sort

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

arr = list(map(int, input("Enter elements: ").split()))


bubble_sort(arr)
print("Sorted list:", arr)

Student Name: Class:

Program Title: Date:

Remark:
Python Program to Sort All Elements Using Quick Sort
(Recursive)

def quicksort(arr, low, high):


if low < high:
Output: pi = partition(arr, low, high)
Enter elements: 90 quicksort(arr, low, pi - 1)
45 06 8 02 95 20 31
Sorted list: [2, 6, 8,
quicksort(arr, pi + 1, high)
20, 31, 45, 90, 95]
def partition(arr, low, high):
pivot = arr[high]
i = low - 1

for j in range(low, high):


if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]

arr[i + 1], arr[high] = arr[high], arr[i + 1]


return i + 1

arr = list(map(int, input("Enter elements: ").split()))


quicksort(arr, 0, len(arr) - 1)
print("Sorted list:", arr)

Student Name: Class:

Program Title: Date:

Remark:
Write a Python program to implement Heap Sort

def heapify(arr, n, i):


largest = i
left = 2 * i + 1
Output: right = 2 * i + 2
Sorted array: [5, 6,
7, 11, 12, 13]
# Check if left child is larger
if left < n and arr[left] > arr[largest]:
largest = left

# Check if right child is larger


if right < n and arr[right] > arr[largest]:
largest = right

# If largest is not root


if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)

def heap_sort(arr):
n = len(arr)

# Build max heap


for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)

# Extract elements
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # Swap
heapify(arr, i, 0)

# Example usage
arr = [12, 11, 13, 5, 6, 7]
heap_sort(arr)
print("Sorted array:", arr)
Student Name: Class:

Program Title: Date:

Remark:

Write a Python program to print all interior (non-leaf) nodes of


a tree

class Node:
def __init__(self, data):
[Link] = data
Output: [Link] = None
Interior (non-leaf) [Link] = None
nodes:
10 5 20

def print_interior_nodes(root):
if root is None:
return

# If NOT a leaf node, print it


if [Link] is not None or [Link] is not None:
print([Link], end=" ")

print_interior_nodes([Link])
print_interior_nodes([Link])

# Example Tree
# 10
# / \
# 5 20
# /\ /
# 3 7 15

root = Node(10)
[Link] = Node(5)
[Link] = Node(20)
[Link] = Node(3)
[Link] = Node(7)
[Link] = Node(15)

print("Interior (non-leaf) nodes:")


print_interior_nodes(root)

Student Name: Class:

Program Title: Date:

Remark:
Q10. Write a python program to check correctness of
paranthesis.

def is_balanced(expr):
stack = []
opening = "({["
closing = ")}]"
pair = {')':'(', '}':'{', ']':'['}

for ch in expr:
if ch in opening: # push opening brackets
[Link](ch)
elif ch in closing: # check closing brackets
if not stack or [Link]() != pair[ch]:
return False

return len(stack) == 0 # stack must be empty

# Main Program
exp = input("Enter expression: ")

if is_balanced(exp):
print("Parentheses are Correct / Balanced")
else:
print("Parentheses are NOT Correct / NOT Balanced")

Output 1:

Enter expression: (a+b)*c-d


Parentheses are Correct / Balanced
Output 2:
Enter expression: (a+b}
Parentheses are NOT Correct / NOT Balanced

You might also like