Python Sparse Matrix and Linked List Operations
Python Sparse Matrix and Linked List Operations
Remark:
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:
Remark:
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:
Remark:
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:
Remark:
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")
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:
Remark:
class CircularSinglyLinkedList:
def __init__(self):
[Link] = None
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:
Remark:
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:
Remark:
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def display(self):
current = [Link]
while current:
print([Link], end="→" if [Link] else "\n")
current = [Link]
print("Linked List:")
[Link]()
Output:
Enter a number: 1234
Linked List:
1→2→3→4
Student Name: Class:
Remark:
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:
Remark:
class Stack:
def __init__(self):
[Link] = []
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
Remark:
Student Name: Class:
Remark:
print("\nIn-order Traversal:")
[Link](root)
print("\nPost-order Traversal:")
[Link](root)
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
# Input elements
print("Enter values to insert into BST (space-separated):")
elements = list(map(int, input().split()))
Remark:
# 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()
Remark:
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
Remark:
print("Adjacency List:")
for key in adj_list:
print(key, ":", adj_list[key])
Student Name: Class:
Remark:
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)
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: "))
Remark:
pos = binary_search(arr, x)
if pos != -1:
print("Element found at index", pos)
else:
print("Element not found")
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]
Remark:
Python Program to Sort All Elements Using Quick Sort
(Recursive)
Remark:
Write a Python program to implement Heap Sort
def heap_sort(arr):
n = len(arr)
# 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:
Remark:
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
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)
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
# 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: