Skip to content

Instantly share code, notes, and snippets.

@niklasvincent
Created September 2, 2016 20:28
Show Gist options
  • Save niklasvincent/17f191b16b2835077d6ddfaca9282899 to your computer and use it in GitHub Desktop.
Save niklasvincent/17f191b16b2835077d6ddfaca9282899 to your computer and use it in GitHub Desktop.
Grokking Algorithms
#!/usr/bin/env python
graph = {
"start": {
"a" : 6,
"b" : 2
},
"a" : {
"fin" : 1
},
"b" : {
"a" : 3,
"fin" : 5
},
"fin" : {}
}
infinity = float("inf")
costs = {
"a" : 6,
"b" : 2,
"fin" : infinity
}
parents = {
"a" : "start",
"b" : "start",
"fin" : None
}
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
assert costs["fin"] == 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment