Professional Documents
Culture Documents
Alaayaan Mustafa B-25342 V1
Alaayaan Mustafa B-25342 V1
Roll NO : B-25342
Q #1:
def get_prime_factors(n):
factors = []
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
Q#2:
class Node:
def _init_(self, val):
self.left = None
self.right = None
self.val = val
def inorder(node):
if node:
inorder(node.left)
print(node.val, end=" ")
inorder(node.right)
def preorder(node):
if node:
print(node.val, end=" ")
preorder(node.left)
preorder(node.right)
def postorder(node):
if node:
postorder(node.left)
postorder(node.right)
print(node.val, end=" ")
def count_nodes(node):
if not node:
return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)
def find_maximum(node):
if not node:
return float('-inf')
return max(node.val, max(find_maximum(node.left), find_maximum(node.right)))
root = Node(values[0])
for val in values[1:]:
node = Node(val)
curr = root
while curr:
if val < curr.val:
if curr.left:
curr = curr.left
else:
curr.left = node
break
else:
if curr.right:
curr = curr.right
else:
curr.right = node
break
total_nodes = count_nodes(root)
max_val = find_maximum(root)
print("\nTotal Elemnents:", total_nodes)
print("Maximum Value:", max_val)
Q#3:
graph = defaultdict(list)
num_nodes = int(input("Enter the number of nodes in the graph: "))
for i in range(num_nodes):
neighbors = list(map(int, input(f"Enter the neighbors of node {i}: ").split()))
graph[i] = neighbors
visited = set()
dfs(0, visited, graph)
if len(visited) == num_nodes:
print("The graph is connected.")
else:
print("The graph is not connected.")
visited = set()
num_components = 0
for i in range(num_nodes):
if i not in visited:
dfs(i, visited, graph)
num_components += 1
print("Number of connected components:", num_components)
Q#4:
class Dictionary:
def __init__(self):
self.entries = {}
def size(self):
return len(self.entries)
def __str__(self):
return str(self.entries)
dictionary = Dictionary()
dictionary.add("apple", 5)
dictionary.add("banana", 10)
dictionary.add("orange", 8)
print("Dictionary:", dictionary)
print("Size:", dictionary.size())
dictionary.remove("banana")
dictionary.remove("grape") # No effect since key doesn't exist
print("Dictionary:", dictionary)
print("Size:", dictionary.size())