DSA Assignment 1-5
DSA Assignment 1-5
class TelephoneBook:
def __init__(self, name, tel_no): # Fixed __init__ spelling
self.name = name
self.tel_no = tel_no
def Insertion_QuadProbing():
hashtable = [None for _ in range(10)]
num_records = int(input("\nEnter number of records: "))
for _ in range(num_records):
n = input("Enter name: ")
t = int(input("Enter telephone no.: "))
hashValue = t % 10 # Primary hash function
i=1
original_hash = hashValue
hashtable[hashValue] = TelephoneBook(n, t)
return hashtable
def Insertion_DoubleHashing():
hashtable = [None for _ in range(10)]
num_records = int(input("\nEnter number of records: "))
for _ in range(num_records):
n = input("Enter name: ")
t = int(input("Enter telephone no.: "))
h1 = t % 10
h2 = 7 - (t % 7)
hashvalue = h1
i=1
hashtable[hashvalue] = TelephoneBook(n, t)
return hashtable
# Show comparisons
print("\n Search Comparison Summary:")
print(f"Quadratic Probing: {comparisons_qp} comparisons")
print(f"Double Hashing: {comparisons_dh} comparisons")
def main():
hash1 = [None for _ in range(10)]
hash2 = [None for _ in range(10)]
while True:
print("\n-------------------------")
print("\t1. Insert Value")
print("\t2. Display")
print("\t3. Search")
print("\t4. Exit")
print("-------------------------")
try:
ch = int(input("Enter choice: "))
except ValueError:
print("Please enter a valid integer.")
continue
if ch == 1:
print("\nSelect collision method:")
print("\t1. Quadratic Probing")
print("\t2. Double Hashing")
try:
c = int(input("Enter choice: "))
if c == 1:
hash1 = Insertion_QuadProbing()
elif c == 2:
hash2 = Insertion_DoubleHashing()
else:
print("Invalid method choice.")
except ValueError:
print("Invalid input. Try again.")
elif ch == 2:
print("\n1. Display Quadratic Probing Table")
print("2. Display Double Hashing Table")
try:
c1 = int(input("Enter choice: "))
if c1 == 1:
Display_Table(hash1, "Quadratic Probing")
elif c1 == 2:
Display_Table(hash2, "Double Hashing")
else:
print("Invalid display choice.")
except ValueError:
print("Invalid input. Try again.")
elif ch == 3:
Search(hash1, hash2)
elif ch == 4:
print("Exiting...")
break
else:
print("! Enter valid choice.")
main()
Output:
Assignment no: 2
set1 = set()
set2 = set()
def add_element():
global set1, set2
for _ in range(set1Size):
element = int(input("Enter element: "))
set1.add(element)
def remove_element():
global set1, set2
if selec == 1:
if elem in set1:
set1.remove(elem)
print("After deletion:", set1)
else:
print("Element does not exist in SET 1.")
elif selec == 2:
if elem in set2:
set2.remove(elem)
print("After deletion:", set2)
else:
print("Element does not exist in SET 2.")
else:
print("Invalid selection.")
def isElementPresent():
global set1, set2
selec = int(input("Choose a set to search in:\n1. SET 1\n2. SET 2\nEnter choice (1/2): "))
elif selec == 2:
print(f"Element {num} exists in SET 2.") if num in set2 else print(f"Element {num} does not exist in
SET 2.")
else:
print("Invalid selection. Please choose 1 or 2.")
def sizeOfSet():
print("\nThe size of SET 1 is", len(set1))
print("The size of SET 2 is", len(set2))
def unionOfSets():
print("\nUnion of sets:", set1.union(set2))
def intersectionOfSets():
print("\nIntersection of sets:", set1.intersection(set2))
def differenceOfSets():
print("\nDifference of sets (SET 1 - SET 2):", set1.difference(set2))
def subSetOrNot():
print("\nIs SET 1 a subset of SET 2?", set1.issubset(set2))
def printElements():
print("\nElements in SET 1:", *set1)
print("Elements in SET 2:", *set2)
def main():
while True:
print("\nSelect an option:")
print("1. Add Elements to Sets")
print("2. Remove Element")
print("3. Check if Element is Present")
print("4. Get Size of Sets")
print("5. Union of Sets")
print("6. Intersection of Sets")
print("7. Difference of Sets")
print("8. Check if Subset")
print("9. Print Elements")
print("10. Exit")
if choice == 1:
add_element()
elif choice == 2:
remove_element()
elif choice == 3:
isElementPresent()
elif choice == 4:
sizeOfSet()
elif choice == 5:
unionOfSets()
elif choice == 6:
intersectionOfSets()
elif choice == 7:
differenceOfSets()
elif choice == 8:
subSetOrNot()
elif choice == 9:
printElements()
elif choice == 10:
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
main()
Output:
Assignment no: 3
class Node:
def __init__(self, name):
self.name = name
self.children = []
def count_nodes(self):
count = 1 # Count self
for child in self.children:
count += child.count_nodes()
return count
def count_operations(self):
# Count 1 operation for printing each node
ops = 1
for child in self.children:
ops += child.count_operations()
return ops
def build_book_tree():
total_chapters = 0
total_sections = 0
total_subsections = 0
for i in range(num_chapters):
chapter_name = input(f"Enter name of Chapter {i + 1}: ")
chapter = Node(chapter_name)
for j in range(num_sections):
section_name = input(f" Enter name of Section {j + 1} in '{chapter_name}': ")
section = Node(section_name)
for k in range(num_subsections):
subsection_name = input(f" Enter name of Subsection {k + 1} in '{section_name}': ")
subsection = Node(subsection_name)
section.add_child(subsection)
chapter.add_child(section)
book.add_child(chapter)
# Main
book_tree, c, s, ss = build_book_tree()
class BST:
def __init__(self):
self.root = None
#main
bst = BST()
while True:
print("\n--- Binary Search Tree Operations ---")
print("1. Insert a new node")
print("2. Display In-order traversal")
print("3. Find longest path from root")
print("4. Find minimum value in BST")
print("5. Mirror the BST")
print("6. Search for a value")
print("7. Exit")
if choice == "1":
val = int(input("Enter value to insert: "))
bst.root = bst.insert(bst.root, val)
print(f"{val} inserted into BST.")
else:
print("Invalid choice! Please enter a number between 1 and 7.")
Output:
Assignment no: 5
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.isThreaded = False
class ThreadedBinaryTree:
def __init__(self):
self.root = None
self.prev = None
self.convert_to_threaded(root.left)
self.prev = root
self.convert_to_threaded(root.right)
def leftmost(self, node):
"""
Find the leftmost node in the tree.
Time Complexity: O(h) (Worst case: skewed tree).
Space Complexity: O(1).
"""
while node and node.left:
node = node.left
return node
tree = ThreadedBinaryTree()
tree.convert_to_threaded(tree.root)
Output:
Assignment no: 6
class Graph:
def __init__(self, num_landmarks):
self.num_landmarks = num_landmarks
self.landmarks = []
self.adj_matrix = [[0] * num_landmarks for _ in range(num_landmarks)]
self.adj_list = {i: [] for i in range(num_landmarks)}
def add_landmarks(self):
print("\nEnter the names of landmarks:")
for i in range(self.num_landmarks):
name = input(f"Enter name of landmark {i+1}: ").strip()
self.landmarks.append(name)
def print_adj_matrix(self):
print("\nAdjacency Matrix Representation:")
print(" " + " ".join(f"{name:<10}" for name in self.landmarks))
for i in range(self.num_landmarks):
row_values = " ".join(f"{self.adj_matrix[i][j]:<10}" for j in range(self.num_landmarks))
print(f"{self.landmarks[i]:<10} {row_values}")
def print_adj_list(self):
print("\nAdjacency List Representation:")
for i in range(self.num_landmarks):
neighbors = [self.landmarks[j] for j in self.adj_list[i]]
print(f"{self.landmarks[i]:<10} → {', '.join(neighbors)}")
# Main Execution
num_landmarks = int(input("Enter the number of landmarks: "))
graph = Graph(num_landmarks)
graph.add_landmarks()
num_edges = int(input("Enter the number of connections (edges): "))
graph.add_edges(num_edges)
graph.print_adj_matrix()
graph.print_adj_list()
Output: