1

我正在一个新的 TI-84 Python 版计算器上编写 Python 代码。它们使用 CircuitPython 的一个版本,对一些非常基本的功能的支持有限。

这包括缺少字典方法,例如items()values()

下面是我的 Dijkstra 算法的原始版本,随后是 TI-Python 中几乎完整的版本。我无法items()使用可行的替代方案转换最后两个实例。

nodes = ('A', 'B', 'C', 'D', 'E')
distances = {
    '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}}


unvisited = {node: None for node in nodes} #using None as +inf
visited = {}
current = 'A' # the start node
currentDistance = 0
unvisited[current] = currentDistance

while True:
    # for the nodes adjacent to the current node.
    for neighbour, distance in distances[current].items():
        # ignore if already visited
        if neighbour not in unvisited:
            continue
        # calculate the total distance to this new node
        newDistance = currentDistance + distance
        # if this adjacent node has a lower distance
        if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
            # update distance to this new, lower distance
            unvisited[neighbour] = newDistance
    # add current node and distance from start to visited list
    visited[current] = currentDistance
    # Remove current node from unvisited list
    del unvisited[current]
    # if all nodes have been visited
    if not unvisited:
        # exit
        break
    # candidates for next node to visit
    print(unvisited.items())
        # print(node[1])
    candidates = [node for node in unvisited.items() if node[1]]
    print(candidates)
    current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]

# print(visited)

print(dict(sorted(visited.items())))

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 = [no for no in un.items() if no[1]]
    cn, cd = sorted(cs, key=lambda x: x[1])[0]

print(dict(sorted(vi.items())))

有人可以解释一下如何重构cs = [no for no in un.items() if no[1]]print(dict(sorted(vi.items())))所以他们不需要.items()or .values()。方法?

4

1 回答 1

3

虽然.items()非常有用,但它相当于迭代键然后查找值。

for k in dict:
    v = dict[k]

相当于

for k, v in dict.items():

因此,粗略的重构

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

将会:

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

请注意,原件可以更好地写为:

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

同样地,

print(dict(sorted(vi.items())))

直接等价于:

print(dict(sorted([k, vi[k] for k in vi]))

但恕我直言,这不是很可读。我会做:

print({k: vi[k] for k in sorted(vi.keys()})
于 2021-09-21T13:05:56.193 回答