Skip to content

Commit e46df69

Browse files
analyze/#8, analyzed optimal_binary_search_tree
1 parent d2113ae commit e46df69

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

dynamic_programming/optimal_binary_search_tree.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@
1919
import sys
2020
from random import randint
2121

22+
flags = {
23+
1: False,
24+
2: False,
25+
3: False,
26+
4: False,
27+
5: False,
28+
6: False
29+
}
2230

2331
class Node:
2432
"""Binary Search Tree Node"""
@@ -118,13 +126,29 @@ def find_optimal_binary_search_tree(nodes):
118126
# Apply Knuth's optimization
119127
# Loop without optimization: for r in range(i, j + 1):
120128
for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root
121-
left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree
122-
right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree
129+
# optimal cost for left subtree
130+
if r != i: # ID: 1
131+
flags[1] = True
132+
left = dp[i][r - 1]
133+
else: # ID: 2
134+
flags[2] = True
135+
left = 0
136+
# optimal cost for right subtree
137+
if r != j: # ID: 3
138+
flags[3] = True
139+
right = dp[r + 1][j]
140+
else: # ID: 4
141+
flags[4] = True
142+
right = 0
143+
123144
cost = left + total[i][j] + right
124145

125-
if dp[i][j] > cost:
146+
if dp[i][j] > cost: # ID: 5
147+
flags[5] = True
126148
dp[i][j] = cost
127149
root[i][j] = r
150+
else: # ID: 6
151+
flags[6] = True
128152

129153
print("Binary search tree nodes:")
130154
for node in nodes:
@@ -141,4 +165,7 @@ def main():
141165

142166

143167
if __name__ == "__main__":
144-
main()
168+
import doctest
169+
doctest.testmod()
170+
171+
print(flags)

0 commit comments

Comments
 (0)