2018-05-07

p116 算法图解,7.1 作业,答案,给大家参看



graph = {}
graph["start"] = {}
graph["start"]["a"] = 5
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["c"] = 4
graph["a"]["d"] = 2
graph["b"] = {}
graph["b"]["a"] = 8
graph["b"]["d"] = 7
#graph["b"]["fin"] = 5
graph["c"] = {}
graph["c"]["fin"] = 3
graph["c"]["d"] = 6
graph["d"] = {}
graph["d"]["fin"] = 1
graph["fin"] = {}
# costs
infinity = float("inf")
costs = {}
costs["a"] = 5
costs["b"] = 2
costs["c"] = infinity
costs["d"] = infinity
costs["fin"] = infinity
# parent
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
# processe
processed = []

#find_lowes
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


#Dijkstra implement
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)

#print(processed)

theway=[]
#print(parents["fin"] )
hh=1

lala = parents["fin"]
theway.append("fin")
theway.append(lala)
while lala != "start" and hh<500: # to Avoid dead loops
    lala =parents[lala]
   # print(lala)
    hh+=7
    #print(hh)
    theway.append(lala)
theway.reverse()
print(theway)
print('the lowest cost is '+str(costs["fin"]) )

结果

$python main.py
['start', 'a', 'd', 'fin']
the lowest cost is 8
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2018-05-07轻松成为效率达人14-笑来老师的高效技巧5-不写就出局第十五篇 加入007不写就出局的你,必然...
    戴维O_O阅读 399评论 0 2
  • 0.2周总结 自评:7分,完成培训ppt及培训,一只大青蛙吃下,且亲子班上完收获非常多 上周目标: 1、跑步三次,...
    rainbow_72dd阅读 194评论 0 0
  • D73棉花 棉花,虽然大家在生活中可能没见过,但在考题中并不陌生。今天我们来看一看纪录片《航拍中国——新疆》中关于...
    林楚楚楚阅读 1,168评论 0 0
  • “弃捐勿复道,努力加餐饭" 先记录一下这个bug修复过程中我做了什么: 为了搞清楚自己的编程能力到底出了什么问题,...
    鎏某某阅读 497评论 0 0
  • 标签标签用于创建供用户输入的 HTML 表单。 form 元素包含一个或多个表单元素,比如: button in...
    初级码农阅读 463评论 0 0