You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dijkstra算法适配TI-Python:重构字典items()方法调用代码

你可以通过直接遍历字典键、手动构造(键, 值)元组的方式替代items()调用,修改方案如下:

1. 替换cs = [no for no in un.items() if no[1]]

原来的逻辑是筛选un中值非空的键值对,替换为遍历键手动取值:

cs = [(k, un[k]) for k in un if un[k]]

2. 替换print(dict(sorted(vi.items())))

先对vi的键排序,再逐个取值构造排序后的字典输出:

sorted_vi = {}
for k in sorted(vi):
    sorted_vi[k] = vi[k]
print(sorted_vi)

修改后的完整TI-Python代码

ns = ("A", "B", "C", "D", "E")
ds = {
    "A": {"B": 6, "D": 1},
    "B": {"A": 6, "C": 5, "D": 2, "E": 2},
    "C": {"B": 5, "E": 5},
    "D": {"A": 1, "B": 2, "E": 1},
    "E": {"B": 2, "C": 5, "D": 1}
}

un = {no: None for no in ns}
vi = {}
cn = "A"
cd = 0
un[cn] = cd

while True:
    for ne in sorted(ds[cn]):
        di = ds[cn][ne]
        if ne not in un:
            continue
        nd = cd + di
        if un[ne] is None or un[ne] > nd:
            un[ne] = nd
    vi[cn] = cd
    del un[cn]
    if not un:
        break
    # 替换后的候选节点生成代码
    cs = [(k, un[k]) for k in un if un[k]]
    cn, cd = sorted(cs, key=lambda x: x[1])[0]

# 替换后的排序输出代码
sorted_vi = {}
for k in sorted(vi):
    sorted_vi[k] = vi[k]
print(sorted_vi)

运行后输出结果和原逻辑完全一致,全程没有调用items()、values()方法,兼容精简版CircuitPython环境。


内容的提问来源于stack exchange,提问作者Robin Andrews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:57:02