0% found this document useful (0 votes)
12 views88 pages

Python Practical Book

The document contains a comprehensive index of Python assignments covering various topics such as basic Python, data structures, and algorithms. Each section includes multiple assignments with programming tasks and example outputs. The assignments focus on practical implementations of concepts like lists, tuples, dictionaries, searching, and sorting algorithms.
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)
12 views88 pages

Python Practical Book

The document contains a comprehensive index of Python assignments covering various topics such as basic Python, data structures, and algorithms. Each section includes multiple assignments with programming tasks and example outputs. The assignments focus on practical implementations of concepts like lists, tuples, dictionaries, searching, and sorting algorithms.
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

Python Index

[Link]. Title Date Sign

1 Assignment:1- Basic Python

2 Assignment:2- Python Tuples

3 Assignment:3- Python Sets

4 Assignment:4- Python
Dictionary

5 Assignment:5- Python Array

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

5 Assignment:5- Linked List


Application

6 Assignment:6- Stack

7 Assignment:7- Applications
Of Stack

8 Assignment:8- Linear
Queue

9 Assignment:9- Circular and


Priority 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

Q2. Write a program which accepts 6 integer values and


prints “DUPLICATES” if any of the values entered are
duplicates otherwise it prints “ALL UNIQUE”. Example: Let 5
integers are (32, 10, 45, 90, 45, 6) then output “DUPLICATES”
to be printed.
Program:
Def check_duplicates(numbers):
If len (numbers) != len(set(numbers)):
Return “ALL UNIQUE”
Number_list = []
Print(“pleas enter 6 integer values:”)
For I in range(6):
Num= int(input(f”enter integer {i+1}:”))
Number_list.append(num)
Result = check_duplicates(number_list)
Print(result)

Output

Q3. Write a program to display following pattern. 1 2 3 4 5 6 7


8 9 10.
Program:
Def display_plattern(rows):
Num = 1
For i in range(1, rows + 1):
For j in range(i):
Print(num, end=’ ‘)
Num += 1
Print()
Rows = 4
Display_pattern(rows):

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

Q2. Write a Python program to create a list of tuples with the


first element as the number and second element as the
square of the number.
Program:
Def create_tuple(n):
Return[(i , I ** 2) for i in range (1, n + 1)]
n=5
tuple_list = create_tuple(n)
print(tuple_list)
Output

Q3. .Copy element 44 and 55 from the following tuple into a


new tuple tuple1 = (11, 22, 33, 44, 55, 66).
Program:
Tuple1 = (11,22,33,44,55,66)
New_tuple = (tuple1[1], tuple1[4])
Print(“new tuple:”, new_tuple)

Output

Q4. .Write a Python program to get the 5th element from


front and 5th element from last of a tuple.
Program:
My_tuple = (11,22,33,44,55,66)
Fifth_from_front = my_tuple[4]
Fifth_from_back = my_tuple[-5]
Print(“5th element from front:”, fifth_from_front)
Print(“5th element from back:”, fifth_from_back)
Output

Q5. Write a Python program to find the repeated items of a


tuple.
Program:
Def find_repeated_items(input_tuple):
Counts = {}
For item in counts:
If item in counts:
Counts[item] += 1
Else:
Counts[item] = 1
Repeated_items = [item for item, count in [Link]() if
count > 1]
Retun repeated_items
My_tuple = (10,20,30,40,50,20,60,70,30)
Repeated = find_repeated_items(my_tuple)
Print(“repeated items:”, repeated)

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

[Link] is the output of following program: sets = {1, 2, 3, 4,


4} print(sets).

Program:
Sets={1,2,3,4,4}
Pritnt(sets)

OUTPUT

2. Write a Python program to do iteration over sets.

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

4. Write a Python program to find maximum and the


minimum value in a set.
Program:
My_set={1,2,3,4}
Print(“original set:”,my_set)
My_set.add(5)
Print(“set after removing 2:”,my_set)
My_set.removing 2:”,my_set)
My_set.discard(10)
Print(“set after trying to remove 10 (discard):”,my_set)

OUTPUT
ASSIGNMENT NO.4

[Link] a Python program to combine two dictionary adding


values for common keys.
Sample Dictionary: d1={'a':100,'b':200,'c':300}
d2={'a':300,'b':200,'d':400} Sample
output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300}).

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:

2. Write a Python script to generate and print a dictionary


that contains a number (Between 1 and n) in the form (x,
x*x).
Sample Dictionary (n = 5) Expected Output : {1: 1, 2: 4, 3: 9,
4: 16, 5: 25}.

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:

3. Write a Python program to create a dictionary from a


string.
Sample-String:’W3resource’ Expected output: {'3': 1, 's': 1, 'r':
2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}

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:

[Link] a python program to reverse the order of the items in


the array.
Porgram:
import array as arr
int_array=[Link]('i',[10,20,30,40,50])
print("Original Array:",int_array)
int_array.reverse()
print("Reversed Array:",int_array)

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:

[Link] a python function to calculate the factorial of a


[Link] function accept the number as an argument.
Program:
def factorial(n):
result=1
for i in range(2, n+1):
result*=i
return result
print("Factorial of number 5=",factorial(5))

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:

[Link] a python function that takes a list and returns a new


list with distict elements from the first list
Sample list:[1, 2 , 2, 3, 3, 3, 3, 4, 5]
Unique list:[1, 2, 3, 4, 5]
Program:
def get_unique_elements(input_list):
unique_list = list(set(input_list))
unique_list.sort()
return unique_list
sample_list = [1, 2, 2, 3, 3, 3, 3, 4, 5]
print("Unique list:", get_unique_elements(sample_list))

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

# Create a new list (single node or multiple values)


def create(self, values):
for val in values:
self.insert_end(val)

# 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

# Display the list


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()
# 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

# Menu driven program


def menu():
dll = DoublyCircularLinkedList()
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")

choice = input("Enter your choice: ")

if choice == '1':
values = list(map(int, input("Enter values separated by
space: ").split()))
[Link](values)

elif choice == '2':


val = int(input("Enter value to insert at beginning: "))
dll.insert_begin(val)
elif choice == '3':
val = int(input("Enter value to insert at end: "))
dll.insert_end(val)

elif choice == '4':


val = int(input("Enter value to delete: "))
[Link](val)

elif choice == '5':


[Link]()

elif choice == '6':


val = int(input("Enter value to search: "))
[Link](val)

elif choice == '7':


print("Exiting program...")
break

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

# Create a new list (single node or multiple values)


def create(self, values):
for val in values:
self.insert_end(val)

# 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

# Display the list


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()

# 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

# Menu driven program


def menu():
dll = DoublyCircularLinkedList()

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")

choice = input("Enter your choice: ")

if choice == '1':
values = list(map(int, input("Enter values separated by
space: ").split()))
[Link](values)

elif choice == '2':


val = int(input("Enter value to insert at beginning: "))
dll.insert_begin(val)

elif choice == '3':


val = int(input("Enter value to insert at end: "))
dll.insert_end(val)

elif choice == '4':


val = int(input("Enter value to delete: "))
[Link](val)

elif choice == '5':


[Link]()

elif choice == '6':


val = int(input("Enter value to search: "))
[Link](val)

elif choice == '7':


print("Exiting program...")
break

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 push(self, data):


if [Link]():
print("Stack Overflow! Cannot push:", data)
else:
[Link] += 1
[Link][[Link]] = data
print(data, "pushed to stack")

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 isFull(self): # For linked list, practically never full unless


memory runs out
return False

def push(self, data):


new_node = Node(data)
new_node.next = [Link]
[Link] = new_node
print(data, "pushed to stack")

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)

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 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 push(self, item):


[Link](item)

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")

choice = input("Enter your choice: ")

if choice == '1':
s = input("Enter a string: ")
print("Reversed String:", reverse_string(s))

elif choice == '2':


s = input("Enter a string: ")
if is_palindrome(s):
print("The string IS a palindrome.")
else:
print("The string is NOT a palindrome.")

elif choice == '3':


expr = input("Enter infix expression: ")
postfix = infix_to_postfix(expr)
print("Postfix Expression:", postfix)

elif choice == '4':


expr = input("Enter postfix expression (single-digit
numbers only): ")
print("Evaluated Result:", evaluate_postfix(expr))

elif choice == '5':


print("Exiting program...")
break

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 enqueue(self, data):


if [Link]():
print("Queue Overflow! Cannot enqueue:", data)
else:
[Link] += 1
if [Link] >= [Link]:
print("Queue reached end, resetting indexes...")
[Link] = [Link] - 1
[Link] = 0
for i in range([Link]):
[Link][i] = [Link][[Link] + i]
[Link][[Link]] = data
[Link] += 1
print(data, "enqueued")

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 :

You might also like