chore(Python): add uniform cost search (#723)
Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com>pull/739/head^2
parent
dd601a7734
commit
bc0569ad09
|
@ -35,6 +35,7 @@
|
|||
- [Linear Search](searching/linear_search.py)
|
||||
- [Ternary Search](searching/ternary_search.py)
|
||||
- [Interpolation Search](searching/interpolation_search.py)
|
||||
- [Uniform Cost Search](searching/uniform_cost_search.py)
|
||||
|
||||
## Sorting
|
||||
- [Bubble Sort](sorting/bubble_sort.py)
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
# this graph to check the algorithm
|
||||
graph={
|
||||
'S':[('A',2),('B',3),('D',5)],
|
||||
'A':[('C',4)],
|
||||
'B':[('D',4)],
|
||||
'C':[('D',1),('G',2)],
|
||||
'D':[('G',5)],
|
||||
'G':[],
|
||||
}
|
||||
|
||||
#to calculate the total cost of path
|
||||
def path_cost(path):
|
||||
total_cost=0
|
||||
for (node, cost) in path:
|
||||
total_cost+=cost
|
||||
return total_cost , path[-1][0]
|
||||
# well sort queue items based on total path
|
||||
#if two items have the same total_cost then sort by node name (alphabetically)
|
||||
|
||||
# uniform cost search
|
||||
def UCS(graph, start, goal):
|
||||
visited=[]
|
||||
queue=[[(start,0)]]
|
||||
while queue:
|
||||
queue.sort(key=path_cost)#sorting by cost
|
||||
path=queue.pop(0)#choosing least cost
|
||||
node=path[-1][0]
|
||||
if node in visited:
|
||||
continue
|
||||
visited.append(node)
|
||||
if node==goal:
|
||||
return path
|
||||
else:
|
||||
adjacent_nodes=graph.get(node,[])
|
||||
for(node2,cost)in adjacent_nodes:
|
||||
new_path=path.copy()
|
||||
new_path.append((node2,cost))
|
||||
queue.append(new_path)
|
||||
|
||||
|
||||
solution= UCS(graph,'S','G')
|
||||
print('solution is ' , solution)
|
||||
print ('cost of solution is ',path_cost(solution)[0])
|
||||
|
Loading…
Reference in New Issue