我在找到使用BFS的最短路徑,我很快得到這個RecursionError: maximum recursion depth exceeded in comparison
,有關如何使用生成器來避免它的任何建議?或者使其迭代是唯一的好選擇?下面如何避免使用生成器的Python中的最大遞歸深度?
代碼:
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
用例:
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
shortest_path(graph, 'A', 'F') # ['A', 'C', 'F']
不,我正在談論使用生成器來處理它們。這是一個例子。我正在使用下一個發生器,但仍達到最大深度。 –
如果您使用小圖(例如您的示例)得到此錯誤,那麼您有邏輯錯誤,而不是資源限制。除非該圖有超過一千個節點,否則不應該是一個問題。 –
你的確切程序在我的機器上運行就好了 – Navidad20