算法图解 第七章练习题

这篇博客主要探讨了《算法图解》第七章的练习题,涉及到Python编程和算法应用。通过A部分和B部分的详细阐述,引导读者自行研究不同字典的特性与操作。

A

#
create = {}
create["A"] = {}
create["A"]["B"] = 5
create["A"]["C"] = 2

create["B"] = {}
create["B"]["D"] = 4
create["B"]["E"] = 2

create["C"] = {}
create["C"]["B"] = 8
create["C"]["E"] = 7

create["D"] = {}
create["D"]["E"] = 6
create["D"]["F"] = 3

create["E"] = {}
create["E"]["F"] = 1

create["F"] = {}

#
inf = float("inf")
costs = {}
costs["B"] = 5
costs["C"] = 2
costs["D"] = inf
costs["E"] = inf
costs["F"] = inf

#
relation = {}
relation["B"] = ["A","C"]
relation["C"] = "A"
relation["D"] = "B"
relation["E"] = ["B","C","D"]
relation["F"] = ""

processed = []

def getlowcost(list):
    lowest_cost = float("inf")
    lowest_node = None
    for node in costs:
        #print(node)
        cost = costs[node]
        #print(cost)
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_node = node
    return lowest_node

node = getlowcost(costs)

while node:
    cost = costs[node]
    neib = create[node]
    #print(neib)
    for i in neib.keys():
        #print(i)
        newcost = cost + neib[i]
        #print(neib[i])
        if costs[i] > newcost:
            costs[i] = newcost
            relation[i] = node
    processed.append(node)
    node = getlowcost(costs)

print(costs)

B

#
create = {}
create["start"] = {}
create["start"]["A"] = 10

create["A"] = {}
create["A"]["C"] = 20

create["B"] = {}
create["B"]["A"] = 1

create["C"] = {}
create["C"]["B"] = 1
create["C"]["end"] = 30

create["end"] = {}

#
inf = float("inf")
costs = {}
costs["A"] = 10
costs["B"] = inf
costs["C"] = inf
costs["end"] = inf

#
relation = {}
relation["A"] = ["start","B"]
relation["B"] = ""
relation["C"] = "A"
relation["end"] = "C"
#
processed = []

def getlowcost(costs):
    lowest_cost = inf
    lowest_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_node = node
    return lowest_node

node = getlowcost(costs)
while node:
    cost = costs[node]
    neib = create[node]
    for i in neib.keys():
        newcost = cost + neib[i]
        if costs[i] > newcost:
            costs[i] = newcost
            relation[i] = node
    processed.append(node)
    node = getlowcost(costs)

print(costs)

代码都是一样的,好像只有字典不一样,大家可以自行研究下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值