Skip to content

Commit bc5cccb

Browse files
committed
code for chapter 7
1 parent 634b54b commit bc5cccb

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# the graph
2+
graph = {}
3+
graph["start"] = {}
4+
graph["start"]["a"] = 6
5+
graph["start"]["b"] = 2
6+
7+
graph["a"] = {}
8+
graph["a"]["fin"] = 1
9+
10+
graph["b"] = {}
11+
graph["b"]["a"] = 3
12+
graph["b"]["fin"] = 5
13+
14+
graph["fin"] = {}
15+
16+
# the costs table
17+
infinity = float("inf")
18+
costs = {}
19+
costs["a"] = 6
20+
costs["b"] = 2
21+
costs["fin"] = infinity
22+
23+
# the parents table
24+
parents = {}
25+
parents["a"] = "start"
26+
parents["b"] = "start"
27+
parents["fin"] = None
28+
29+
processed = []
30+
31+
def find_lowest_cost_node(costs):
32+
lowest_cost = float("inf")
33+
lowest_cost_node = None
34+
# Go through each node.
35+
for node in costs:
36+
cost = costs[node]
37+
# If it's the lowest cost so far and hasn't been processed yet...
38+
if cost < lowest_cost and node not in processed:
39+
# ... set it as the new lowest-cost node.
40+
lowest_cost = cost
41+
lowest_cost_node = node
42+
return lowest_cost_node
43+
44+
# Find the lowest-cost node that you haven't processed yet.
45+
node = find_lowest_cost_node(costs)
46+
# If you've processed all the nodes, this while loop is done.
47+
while node is not None:
48+
cost = costs[node]
49+
# Go through all the neighbors of this node.
50+
neighbors = graph[node]
51+
for n in neighbors.keys():
52+
new_cost = cost + neighbors[n]
53+
# If it's cheaper to get to this neighbor by going through this node...
54+
if costs[n] > new_cost:
55+
# ... update the cost for this node.
56+
costs[n] = new_cost
57+
# This node becomes the new parent for this neighbor.
58+
parents[n] = node
59+
# Mark the node as processed.
60+
processed.append(node)
61+
# Find the next node to process, and loop.
62+
node = find_lowest_cost_node(costs)
63+
64+
print "Cost from the start to each node:"
65+
print costs
66+

0 commit comments

Comments
 (0)