Python Practical Book
Python Practical Book
4 Assignment:4- Python
Dictionary
6 Assignment:6- Python
Functions
Data Structures Index
[Link]. Title Date Sign
1 Assignment:1- Searching
Algorithms
2 Assignment:2- Sorting
Algorithms
3 Assignment:3- Singly
Linked List
4 Assignment:4- Doubly
Linked List
6 Assignment:6- Stack
7 Assignment:7- Applications
Of Stack
8 Assignment:8- Linear
Queue
10 Assignment:10- Tree
11 Assignment:11- Graph
ASSIGNMENT NO : 1
Q1. Write a Python Program to Calculate the Average of
Numbers in a Given List. 2).
Program:
Def calculate_average(number):
If not numbers:
Return 0
Return sum(numbers)/ len (numbers)
Number_list = [10,20,30,40,50]
Average = calculate_average(number_list)
Print(f”the average of{number_list } is {average:.2f}”)
output
Output
Output
ASSIGNMENT NO : 2
Q1. Reverse the following tuple aTup = (10, 20, 30, 40, 50).
Program:
aTup = (10,20,30,40,50)
reversed_tup = atup [:: - 1]
print(“original tuple : “, atup)
print(“reversed tuple :”, reversed_tup)
Output
Output
Output
Q6. Write a Python program to check whether an element
exists within a tuple.
Program:
Def check_element_i_tuple(input_tuple, element):
Return element in input_tuple
My_tuple = (10,20,30,40,50)
Element_to_check = 30
If check_element_in_tuple(my_tuple, element_to_check):
Print(f”{element_to_check} exists in the tuple”)
Else:
Print(f”{element_to_check} does not exist in the tuple”)
Output
ASSIGNMENT NO : 3
Program:
Sets={1,2,3,4,4}
Pritnt(sets)
OUTPUT
Program:
My_set={1,2,3,4,5}
Print(“”iterating over the set:”)
For item in my_set:
Print(item)
OUTPUT
3. Write a Python program to add and remove operation on
set.
Program:
My_set={1,2,3,4}
Print(“oridinal set :”,my_set)
My_set.add(5)
Print(“set after removing 2:”,my_set)
My_set.discard(10)
Print(“set after trying to remove 10 (discard) :”,my_set)
OUTPUT
OUTPUT
ASSIGNMENT NO.4
Program:
from collections import Counter
d1={'a':100,'b':200,'c':300}
d2={'a':200,'b':540,'d':400}
combined=Counter(d1)+Counter(d2)
print("Adding two dictionary=",combined)
output:
Program:
def square_root(n):
squ_dict={x:x*x for x in range(1,n+1)}
return squ_dict
n=5
result_dict=square_root(n)
print("Square of 5 numbers=",result_dict)
output:
Program:
string='W3resource'
string=[Link]()
char_count={}
for char in string:
if char in char_count:
char_count[char]+=1
else:
char_count[char]=1
print("Character count=",char_count)
Output:
ASSIGNMENT NO.5
[Link] a python program to create an array of 5 integers and
display the array elements. Access individual elements
through indexes.
Program:
import array as arr
int_array=[Link]('i',[10,20,30,40,50])
print("Array elements:")
for index in range(len(int_array)):
print(f"Element at index{index}:{int_array[index]}")
print("\nAccsseing individual elements:")
print("Element at index 0:",int_array[0])
print("Element at index 1:",int_array[1])
print("Element at index 2:",int_array[2])
print("Element at index 3:",int_array[3])
print("Element at index 4:",int_array[4])
output:
[Link] a python program to get the number of occurrences
of specified elements in an array.
Program:
import array as arr
def count_occurrence(input_array,element):
return input_array.count(element)
int_array=[Link]('i',[10,20,30,40,50,10,10])
element_to_count=10
occurrence=count_occurrence(int_array,element_to_count)
print(f"The number of occurrences of {element_to_count} in
the arra is:{occurrence}")
Output:
Output:
ASSIGNMENT NO.6
[Link] a python function to sum of all the elements in a list
Program:
def sum_of_list(elements):
return sum(elements)
print("Sum of the list=",sum_of_list([5,6,7,8,10]))
Output:
Output:
[Link] a python function to check whether a number falls
within a given range.
Program:
def is_in_range(num,low,high):
return low<=num<=high
print("Number falls in range(5,1,10)=",is_in_range(5,1,10))
print("Number falls in range(15,1,10)=",is_in_range(15,1,10))
Output:
Output:
Data Structure
Assignment 1
[Link] of searching algorithms to search an
element using:
Linear Search, Binary Search.
Linear Search:
Program:
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1
arr = [5, 3, 8, 4, 2]
target = 4
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found.")
Output:
Binary Search:
Program:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [2, 3, 4, 5, 8] # Must be sorted for binary search
target = 5
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found.")
Output:
Assignment 2
[Link] of sorting algorithms: Bubble Sort,
Insertion Sort , QuickSort, Merge Sort.
Bubble Sort:
Program:
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] # Swap
return arr
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("Bubble Sort Result:", sorted_arr)
Output:
Insertion Sort:
Program:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j] # Shift element to right
j -= 1
arr[j + 1] = key # Insert key at correct position
return ar
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = insertion_sort(arr)
print("Insertion Sort Result:", sorted_arr)
Output:
Quick Sort:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(arr)
print("Quick Sort Result:", sorted_arr)
Output:
Merge Sort:
Program:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
[Link](left[i])
i += 1
else:
[Link](right[j])
j += 1
[Link](left[i:])
[Link](right[j:])
return result
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = merge_sort(arr)
print("Merge Sort Result:", sorted_arr)
Output:
Assignment 3
[Link] implementation of Singly Linked List to perform
following operations: Create, Insert, Delete, Display, Search,
Reverse 2. Create a list in the sorted order.
Program:
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class SinglyLinkedList:
def __init__(self):
[Link] = None
def create(self, data):
new_node = Node(data)
if [Link] is None:
[Link] = new_node
else:
current = [Link]
while [Link]:
current = [Link]
[Link] = new_node
def insert(self, data):
new_node = Node(data)
if [Link] is None or [Link] >= new_node.data:
new_node.next = [Link]
[Link] = new_node
return
current = [Link]
while [Link] and [Link] < new_node.data:
current = [Link]
new_node.next = [Link]
[Link] = new_node
def delete(self, key):
current = [Link]
if current and [Link] == key:
[Link] = [Link]
current = None
return
prev = None
while current and [Link] != key:
prev = current
current = [Link]
if current is None:
print("Key not found.")
return
[Link] = [Link]
current = None
def display(self):
current = [Link]
if not current:
print("List is empty.")
return
while current:
print([Link], end=" -> ")
current = [Link]
print("None")
def search(self, key):
current = [Link]
while current:
if [Link] == key:
print(f"{key} found in the list.")
return
current = [Link]
print(f"{key} not found in the list.")
def reverse(self):
prev = None
current = [Link]
while current:
next_node = [Link]
[Link] = prev
prev = current
current = next_node
[Link] = prev
if __name__ == "__main__":
sll = SinglyLinkedList()
[Link](5)
[Link](3)
[Link](7)
[Link](2)
[Link](4)
print("Linked List:")
[Link]()
print("After deleting 3:")
[Link](3)
[Link]()
print("Searching for 4:")
[Link](4)
print("Reversing the list:")
[Link]()
[Link]()
Output:
Assignment 4
[Link] Linked List - Dynamic implementation of Doubly
circular Linked List to perform following operations: Create,
Insert, Delete, Display, Search.
PROGRAM :
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
class DoublyCircularLinkedList:
def __init__(self):
[Link] = None
# Insert at beginning
def insert_begin(self, data):
new_node = Node(data)
if [Link] is None:
new_node.next = new_node.prev = new_node
[Link] = new_node
return
last = [Link]
new_node.next = [Link]
new_node.prev = last
[Link] = new_node
[Link] = new_node
[Link] = new_node
# Insert at end
def insert_end(self, data):
new_node = Node(data)
if [Link] is None:
new_node.next = new_node.prev = new_node
[Link] = new_node
return
last = [Link]
new_node.next = [Link]
new_node.prev = last
[Link] = new_node
[Link] = new_node
# Delete a node
def delete(self, key):
if [Link] is None:
print("List is empty")
return
curr = [Link]
prev_node = None
while True:
if [Link] == key:
if [Link] == curr: # Only one node
[Link] = None
return
if curr == [Link]:
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
return
prev_node = curr
curr = [Link]
if curr == [Link]:
print("Value not found!")
return
if choice == '1':
values = list(map(int, input("Enter values separated by
space: ").split()))
[Link](values)
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 5
[Link] List Applications - Merge two sorted lists.
PROGRAM :
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
class DoublyCircularLinkedList:
def __init__(self):
[Link] = None
# Insert at beginning
def insert_begin(self, data):
new_node = Node(data)
if [Link] is None:
new_node.next = new_node.prev = new_node
[Link] = new_node
return
last = [Link]
new_node.next = [Link]
new_node.prev = last
[Link] = new_node
[Link] = new_node
[Link] = new_node
# Insert at end
def insert_end(self, data):
new_node = Node(data)
if [Link] is None:
new_node.next = new_node.prev = new_node
[Link] = new_node
return
last = [Link]
new_node.next = [Link]
new_node.prev = last
[Link] = new_node
[Link] = new_node
# Delete a node
def delete(self, key):
if [Link] is None:
print("List is empty")
return
curr = [Link]
prev_node = None
while True:
if [Link] == key:
if [Link] == curr: # Only one node
[Link] = None
return
if curr == [Link]:
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
return
prev_node = curr
curr = [Link]
if curr == [Link]:
print("Value not found!")
return
# Search an element
def search(self, key):
if [Link] is None:
print("List is empty")
return False
temp = [Link]
while True:
if [Link] == key:
print(f"Value {key} found in the list")
return True
temp = [Link]
if temp == [Link]:
break
print(f"Value {key} not found in the list")
return False
while True:
print("\n===== Doubly Circular Linked List Menu =====")
print("1. Create")
print("2. Insert at Beginning")
print("3. Insert at End")
print("4. Delete")
print("5. Display")
print("6. Search")
print("7. Exit")
if choice == '1':
values = list(map(int, input("Enter values separated by
space: ").split()))
[Link](values)
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 6
[Link] - Static and Dynamic implementation of Stack to
perform following operations: Init, Push, Pop, Isempty, Isfull
PROGRAM :
class StaticStack:
def __init__(self, capacity):
[Link] = capacity
[Link] = [None] * capacity
[Link] = -1
def isEmpty(self):
return [Link] == -1
def isFull(self):
return [Link] == [Link] - 1
def pop(self):
if [Link]():
print("Stack Underflow! Nothing to pop")
else:
popped = [Link][[Link]]
[Link][[Link]] = None
[Link] -= 1
print("Popped:", popped)
def display(self):
if [Link]():
print("Stack is empty")
else:
print("Stack:", [Link][:[Link] + 1])
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class DynamicStack:
def __init__(self):
[Link] = None
def isEmpty(self):
return [Link] is None
def pop(self):
if [Link]():
print("Stack Underflow! Nothing to pop")
else:
popped = [Link]
[Link] = [Link]
print("Popped:", popped)
def display(self):
if [Link]():
print("Stack is empty")
else:
temp = [Link]
print("Stack:", end=" ")
while temp:
print([Link], end=" -> ")
temp = [Link]
print("None")
def menu():
print("Choose implementation:")
print("1. Static Stack")
print("2. Dynamic Stack")
impl_choice = input("Enter choice: ")
stack = None
if impl_choice == '1':
capacity = int(input("Enter capacity of stack: "))
stack = StaticStack(capacity)
elif impl_choice == '2':
stack = DynamicStack()
else:
print("Invalid choice!")
return
while True:
print("\n===== Stack Menu =====")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Check isEmpty")
print("5. Check isFull")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
val = int(input("Enter value to push: "))
[Link](val)
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 7
[Link] of Stack - 1. Implementation of an algorithm
that reverses string of characters using stack and checks
whether a string is a palindrome. 2. Infix to Postfix
conversion. Evaluation of postfix expression.
PROGRAM :
class Stack:
def __init__(self):
[Link] = []
def isEmpty(self):
return len([Link]) == 0
def pop(self):
if not [Link]():
return [Link]()
return None
def peek(self):
if not [Link]():
return [Link][-1]
return None
def size(self):
return len([Link])
def reverse_string(s):
stack = Stack()
for ch in s:
[Link](ch)
rev = ""
while not [Link]():
rev += [Link]()
return rev
def is_palindrome(s):
return s == reverse_string(s)
def precedence(op):
if op in ['+', '-']:
return 1
if op in ['*', '/']:
return 2
if op == '^':
return 3
return 0
def infix_to_postfix(expression):
stack = Stack()
result = ""
for ch in expression:
if [Link](): # operand
result += ch
elif ch == '(':
[Link](ch)
elif ch == ')':
while not [Link]() and [Link]() != '(':
result += [Link]()
[Link]() # remove '('
else: # operator
while (not [Link]() and
precedence([Link]()) >= precedence(ch)):
result += [Link]()
[Link](ch)
while not [Link]():
result += [Link]()
return result
def evaluate_postfix(expression):
stack = Stack()
for ch in expression:
if [Link]():
[Link](int(ch))
else:
val2 = [Link]()
val1 = [Link]()
if ch == '+':
[Link](val1 + val2)
elif ch == '-':
[Link](val1 - val2)
elif ch == '*':
[Link](val1 * val2)
elif ch == '/':
[Link](val1 // val2) # integer division
elif ch == '^':
[Link](val1 ** val2)
return [Link]()
def menu():
while True:
print("\n===== Stack Applications Menu =====")
print("1. Reverse a String")
print("2. Check Palindrome")
print("3. Infix to Postfix Conversion")
print("4. Evaluate Postfix Expression")
print("5. Exit")
if choice == '1':
s = input("Enter a string: ")
print("Reversed String:", reverse_string(s))
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 8
[Link] Queue - Static and Dynamic implementation of
linear Queue to perform following operations: Init, enqueue,
dequeue, IsEmpty, IsFull.
PROGRAM :
class StaticQueue:
def __init__(self, capacity):
[Link] = capacity
[Link] = [None] * capacity
[Link] = 0
[Link] = -1
[Link] = 0
def isEmpty(self):
return [Link] == 0
def isFull(self):
return [Link] == [Link]
def dequeue(self):
if [Link]():
print("Queue Underflow! Nothing to dequeue")
else:
val = [Link][[Link]]
[Link][[Link]] = None
[Link] += 1
[Link] -= 1
print("Dequeued:", val)
def display(self):
if [Link]():
print("Queue is empty")
else:
print("Queue:", [Link][[Link]:[Link] + 1])
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class DynamicQueue:
def __init__(self):
[Link] = None
[Link] = None
def isEmpty(self):
return [Link] is None
def isFull(self):
return False
def enqueue(self, data):
new_node = Node(data)
if [Link] is None:
[Link] = [Link] = new_node
else:
[Link] = new_node
[Link] = new_node
print(data, "enqueued")
def dequeue(self):
if [Link]():
print("Queue Underflow! Nothing to dequeue")
else:
val = [Link]
[Link] = [Link]
if [Link] is None:
[Link] = None
print("Dequeued:", val)
def display(self):
if [Link]():
print("Queue is empty")
else:
temp = [Link]
print("Queue:", end=" ")
while temp:
print([Link], end=" -> ")
temp = [Link]
print("None")
def menu():
print("Choose implementation:")
print("1. Static Queue")
print("2. Dynamic Queue")
impl_choice = input("Enter choice: ")
queue = None
if impl_choice == '1':
capacity = int(input("Enter capacity of queue: "))
queue = StaticQueue(capacity)
elif impl_choice == '2':
queue = DynamicQueue()
else:
print("Invalid choice!")
return
while True:
print("\n===== Queue Menu =====")
print("1. Enqueue")
print("2. Dequeue")
print("3. Display")
print("4. Check isEmpty")
print("5. Check isFull")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
val = int(input("Enter value to enqueue: "))
[Link](val)
elif choice == '2':
[Link]()
elif choice == '3':
[Link]()
elif choice == '4':
print("isEmpty:", [Link]())
elif choice == '5':
print("isFull:", [Link]())
elif choice == '6':
print("Exiting program...")
break
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 9
[Link] and Priority Queue 1. Implementation of circular
queue 2.
Implementation of priority queue
PROGRAM :
class CircularQueue:
def __init__(self, capacity):
[Link] = capacity
[Link] = [None] * capacity
[Link] = [Link] = -1
def isEmpty(self):
return [Link] == -1
def isFull(self):
return ([Link] + 1) % [Link] == [Link]
def enqueue(self, data):
if [Link]():
print("Circular Queue Overflow!")
elif [Link]():
[Link] = [Link] = 0
[Link][[Link]] = data
print(data, "enqueued")
else:
[Link] = ([Link] + 1) % [Link]
[Link][[Link]] = data
print(data, "enqueued")
def dequeue(self):
if [Link]():
print("Circular Queue Underflow!")
elif [Link] == [Link]:
val = [Link][[Link]]
[Link] = [Link] = -1
print("Dequeued:", val)
else:
val = [Link][[Link]]
[Link] = ([Link] + 1) % [Link]
print("Dequeued:", val)
def display(self):
if [Link]():
print("Queue is empty")
else:
print("Circular Queue:", end=" ")
i = [Link]
while True:
print([Link][i], end=" ")
if i == [Link]:
break
i = (i + 1) % [Link]
print()
class PriorityQueue:
def __init__(self):
[Link] = []
def isEmpty(self):
return len([Link]) == 0
def isFull(self):
return False
def enqueue(self, data, priority):
[Link]((priority, data))
[Link](reverse=True)
print(data, "enqueued with priority", priority)
def dequeue(self):
if [Link]():
print("Priority Queue Underflow!")
else:
priority, data = [Link](0)
print("Dequeued:", data, "with priority", priority)
def display(self):
if [Link]():
print("Queue is empty")
else:
print("Priority Queue:", end=" ")
for priority, data in [Link]:
print(f"({data}, p={priority})", end=" ")
print()
def menu():
print("Choose implementation:")
print("1. Circular Queue")
print("2. Priority Queue")
impl_choice = input("Enter choice: ")
queue = None
if impl_choice == '1':
capacity = int(input("Enter capacity of Circular Queue: "))
queue = CircularQueue(capacity)
elif impl_choice == '2':
queue = PriorityQueue()
else:
print("Invalid choice!")
return
while True:
print("\n===== Queue Menu =====")
print("1. Enqueue")
print("2. Dequeue")
print("3. Display")
print("4. Check isEmpty")
print("5. Check isFull")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
if isinstance(queue, CircularQueue):
val = int(input("Enter value to enqueue: "))
[Link](val)
else:
val = int(input("Enter value to enqueue: "))
priority = int(input("Enter priority: "))
[Link](val, priority)
elif choice == '2':
[Link]()
elif choice == '3':
[Link]()
elif choice == '4':
print("isEmpty:", [Link]())
elif choice == '5':
print("isFull:", [Link]())
elif choice == '6':
print("Exiting program...")
break
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 10
Q. Tree Travarsals, operations etc
PROGRAM :
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
class BinaryTree:
def __init__(self):
[Link] = None
def insert(self, data):
if [Link] is None:
[Link] = Node(data)
else:
self._insert([Link], data)
def _insert(self, node, data):
if data < [Link]:
if [Link] is None:
[Link] = Node(data)
else:
self._insert([Link], data)
else:
if [Link] is None:
[Link] = Node(data)
else:
self._insert([Link], data)
def inorder(self, node):
if node:
[Link]([Link])
print([Link], end=" ")
[Link]([Link])
def preorder(self, node):
if node:
print([Link], end=" ")
[Link]([Link])
[Link]([Link])
def postorder(self, node):
if node:
[Link]([Link])
[Link]([Link])
print([Link], end=" ")
def menu():
tree = BinaryTree()
while True:
print("\n--- Binary Tree Menu ---")
print("1. Insert Node")
print("2. Inorder Traversal")
print("3. Preorder Traversal")
print("4. Postorder Traversal")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
data = int(input("Enter value to insert: "))
[Link](data)
elif choice == '2':
print("Inorder Traversal: ", end="")
[Link]([Link])
print()
elif choice == '3':
print("Preorder Traversal: ", end="")
[Link]([Link])
print()
elif choice == '4':
print("Postorder Traversal: ", end="")
[Link]([Link])
print()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
menu()
OUTPUT :
ASSIGNMENT 11
[Link] indegree and out degree of a given graph.
PROGRAM :
def add_edge(graph, u, v):
if u in graph:
graph[u].append(v)
else:
graph[u] = [v]
# Ensure the vertex v is in the graph even if it has no
outgoing edges
if v not in graph:
graph[v] = []
def calculate_outdegree(graph, vertex):
return len(graph[vertex])
def calculate_indegree(graph, vertex):
indegree = 0
for v in graph:
if vertex in graph[v]:
indegree += 1
return indegree
def display_graph(graph):
print("Graph adjacency list:")
for key in graph:
print(f"{key} -> {graph[key]}")
def menu():
graph = {}
while True:
print("\n--- Directed Graph Menu ---")
print("1. Add Edge")
print("2. Calculate Outdegree of a vertex")
print("3. Calculate Indegree of a vertex")
print("4. Display Graph")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
u = input("Enter source vertex: ")
v = input("Enter destination vertex: ")
add_edge(graph, u, v)
elif choice == '2':
vertex = input("Enter vertex to find outdegree: ")
if vertex in graph:
print(f"Outdegree of {vertex} is
{calculate_outdegree(graph, vertex)}")
else:
print("Vertex not found in graph!")
elif choice == '3':
vertex = input("Enter vertex to find indegree: ")
if vertex in graph:
print(f"Indegree of {vertex} is
{calculate_indegree(graph, vertex)}")
else:
print("Vertex not found in graph!")
elif choice == '4':
display_graph(graph)
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice! Try again.")
if __name__ == "__main__":
menu()
output :