我正在一个新的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()或.values()了。方法?
发布于 2021-09-21 13:05:56
虽然.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]))但这不是很好读的IMHO。我会这样做:
print({k: vi[k] for k in sorted(vi.keys()})https://stackoverflow.com/questions/69269396
复制相似问题