ASSIGNMENT No- 08
Name- Om Santosh Songire
Roll No - 128
Batch - B3
Given sequence k= k1<k2< ...<kn of n sorted keys, with a search
probability pi foreach key ki. Build the Binary search tree that has the
least search cost given the access probability for each key.
Program:
def optimal_bst(keys,
probs): n = len(keys)
cost = [[0] * n for _ in
range(n)] root = [[0] * n for _ in
range(n)]
for i in range(n):
cost[i][i] = probs[i]
root[i][i] = i
for L in range(2, n + 1):
for i in range(n - L + 1):
j=i+L-1
cost[i][j] = float('inf')
total_prob = sum(probs[i:j +
1]) for r in range(i, j + 1):
left = cost[i][r - 1] if r > i else 0
right = cost[r + 1][j] if r < j
else 0 total = left + right +
total_prob if total < cost[i][j]:
cost[i][j] = total
return cost[0][n - 1], root
print("4. Exit")
def print_obst_structure(root, keys, i, j,
parent=None,is_left=True):
if i > j:
return
r = root[i][j]
current = keys[r]
if parent is None:
print(f"Root: {current}")
else:
direction = "left" if is_left else "right"
print(f"{current} is the {direction} child of {parent}")
print_obst_structure(root, keys, i, r - 1, current, True)
print_obst_structure(root, keys, r + 1, j, current, False)
def menu():
keys = []
probs = []
while True:
print("\n--- Optimal BST Menu ---
") print("1. Add key and
probability") print("2. Display
input")
print("3. Construct Optimal BST")
print(“4. Exit”)
choice = input("Enter your choice: ")
if choice == '1':
key = int(input("Enter the key (integer): "))
prob = float(input("Enter the search probability: ")
[Link](key)
[Link](prob)
zipped = list(zip(keys, probs))
[Link]() # keep keys sorted
keys, probs = zip(*zipped)
keys, probs = list(keys), list(probs)
print("Key and probability added.")
elif choice == '2': if
keys:
print("Sorted Keys:", keys)
print("Probabilities:", probs)
else:
print("No keys entered yet.")
elif choice == '3': if
not keys:
print("No data available. Add keys first.")
continue
cost, root = optimal_bst(keys, probs)
print(f"\nMinimum Search Cost: {cost}")
print("\nOptimal BST Structure:")
print_obst_structure(root, keys, 0, len(keys) - 1)
elif choice == ‘4’:
print("Exiting program.")
break
else:
print("Invalid choice. Try again.")
# Run the menu
menu()
Output:
--- Optimal BST Menu ---
1. Add key and probability
2. Display input
3. Construct Optimal BST
4. Exit
Enter your choice: 1
Enter the key (integer): 10
Enter the search probability: 0.1
Key and probability added.
--- Optimal BST Menu ---
1. Add key and probability
2. Display input
3. Construct Optimal BST
4. Exit
Enter your choice: 1
Enter the key (integer): 20
Enter the search probability: 0.2
--- Optimal BST Menu ---
1. Add key and probability
2. Display input
3. Construct Optimal BST
4. Exit
Enter your choice: 1
Enter the key (integer): 30
Enter the search probability: 0.4
Key and probability added.
--- Optimal BST Menu ---
1. Add key and probability
2. Display input
3. Construct Optimal BST
4. Exit
Enter your choice: 1
Enter the key (integer): 40
Enter the search probability: 0.3
Key and probability added.
--- Optimal BST Menu ---
1. Add key and probability
2. Display input
3. Construct Optimal BST
4. Exit
Enter your choice: 2
Sorted Keys: [10, 20, 30, 40]
Probabilities: [0.1, 0.2, 0.4, 0.3]