基本错误是递归调用的结果需要返回,如果它没有导致死胡同。
此外,如果该点没有邻居,G[pt]
则会引发一个。这可以通过使用轻松修复。IndexError
pt
dict.get
def hamilton(G, size, pt, path=[]):
print('hamilton called with pt={}, path={}'.format(pt, path))
if pt not in set(path):
path.append(pt)
if len(path)==size:
return path
for pt_next in G.get(pt, []):
res_path = [i for i in path]
candidate = hamilton(G, size, pt_next, res_path)
if candidate is not None: # skip loop or dead end
return candidate
print('path {} is a dead end'.format(path))
else:
print('pt {} already in path {}'.format(pt, path))
# loop or dead end, None is implicitly returned
例子
>>> G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
>>> hamilton(G, 4, 1)
hamilton called with pt=1, path=[]
hamilton called with pt=2, path=[1]
hamilton called with pt=1, path=[1, 2]
pt 1 already in path [1, 2]
hamilton called with pt=3, path=[1, 2]
hamilton called with pt=1, path=[1, 2, 3]
pt 1 already in path [1, 2, 3]
hamilton called with pt=2, path=[1, 2, 3]
pt 2 already in path [1, 2, 3]
hamilton called with pt=4, path=[1, 2, 3]
[1, 2, 3, 4]
>>> G = {1:[2], 2:[3,4], 4:[3]}
>>> hamilton(G, 4, 1)
hamilton called with pt=1, path=[]
hamilton called with pt=2, path=[1]
hamilton called with pt=3, path=[1, 2]
path [1, 2, 3] is a dead end
hamilton called with pt=4, path=[1, 2]
hamilton called with pt=3, path=[1, 2, 4]
[1, 2, 4, 3]
>>> G = {1:[2], 2:[3,4], 4:[3]}
>>> hamilton(G, 4, 2)
hamilton called with pt=2, path=[]
hamilton called with pt=3, path=[2]
path [2, 3] is a dead end
hamilton called with pt=4, path=[2]
hamilton called with pt=3, path=[2, 4]
path [2, 4, 3] is a dead end
path [2, 4] is a dead end
path [2] is a dead end
None
请注意,由于“可变默认参数”问题,多次使用该函数可能会导致错误结果。但这不是这个答案的范围。