我正在尝试编写Dijkstra最短路径算法的变体。在这样做时,我想将最短路径距离初始化为math.inf
,并为任何未见过的键返回此值。
我正在使用一个defaultdict,初始化为defaultdict(lambda:math.inf)
,希望为新键返回一个无限的值。
但是,在下面的示例中我看到返回None值。
初始化:
shortest_paths = defaultdict(lambda:math.inf)
shortest_paths[k] = 0
print(f"Initial values for shortest_paths = {shortest_paths}")
这个打印:
Initial values for shortest_paths = defaultdict(<function Solution.networkDelayTime.<locals>.<lambda> at 0x1044818b0>, {2: 0})
调用:
print(f"n={n} and shortest_paths.get(n) = {shortest_paths.get(n)}")
这个打印:
n=1 and shortest_paths.get(n) = None
这最终导致None对象和整数值之间的比较,从而破坏了我的代码。
shortest_paths[n] = min(shortest_paths.get(n), shortest_paths.get(current) + dist)
导致:
TypeError: '<' not supported between instances of 'int' and 'NoneType'
我想弄清楚的是defaultdict的值是如何没有初始化的。
粘贴在REPL上的代码运行良好。我正在使用VSCode,如果这是相关的。
defaultdict
的要点是您始终使用括号访问—.get(...)
保留其原始语义(继承自dict
):
>>> shortest_paths = defaultdict(lambda:math.inf)
>>> shortest_paths[5]
inf
>>> shortest_paths.get(5)
inf
>>> print(shortest_paths.get(6))
None