-
Notifications
You must be signed in to change notification settings - Fork 0
/
AOAlgorithm.py
72 lines (62 loc) · 2.21 KB
/
AOAlgorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
AO*Algorithm:
'''
def Cost(H, condition, weight=1):
cost = {}
if 'AND' in condition:
AND_nodes = condition['AND']
Path_A = ' AND '.join(AND_nodes)
PathA = sum(H[node] + weight for node in AND_nodes)
cost[Path_A] = PathA
if 'OR' in condition:
OR_nodes = condition['OR']
Path_B = ' OR '.join(OR_nodes)
PathB = min(H[node] + weight for node in OR_nodes)
cost[Path_B] = PathB
return cost
def update_cost(H, Conditions, weight=1):
Main_nodes = list(Conditions.keys())
Main_nodes.reverse()
least_cost = {}
for key in Main_nodes:
condition = Conditions[key]
print(key, ':', Conditions[key], '>>>', Cost(H, condition, weight))
c = Cost(H, condition, weight)
H[key] = min(c.values())
least_cost[key] = Cost(H, condition, weight)
return least_cost
# Function to print the shortest path
def shortest_path(Start, Updatesd_cost, H):
Path = Start
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_cost)
# Find minimum path key
Next = key[Index]
# Add to path for OR path
if len(Next.split()) == 1:
Start = Next
Path += ' <-- ' + shortest_path(Start, Updated_cost, H)
# Add to path for AND path
else:
Path += ' <-- (' + Next + ') '
Start = Next.split()[0]
Path += '[' + shortest_path(Start, Updated_cost, H) + ' + '
Start = Next.split()[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'
return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I': 0, 'J': 0}
Conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
# G for the node
weight = 1
print('Updated Cost:')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*' * 75)
print('Shortest Path:\n', shortest_path('A', Updated_cost, H))