answers = []
def search(visit_order, nodes_to_visit, distance):
if len(nodes_to_visit) == 0:
print visit_order
answers.append(visit_order)
return
else:
for node in nodes_to_visit:
nodes_to_visit.remove(node)
visit_order.append(node)
search(visit_order, nodes_to_visit, 0)
visit_order.remove(node)
nodes_to_visit.append(node)
search([],nodes, 0)
print answers
我有一個全局列表answers
和遞歸函數,通過給定的nodes_to_visit
不勝枚舉時,有沒有更多的nodes_to_visit
這將增加visit_order
到answers
列表。全球列表附加任何
當我在打印之前打印Visit_order
時,我得到一個正確的值。但是,當我打印answers
時,我只能得到列表,如[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
。問題是什麼?例如,如果我給搜索([],[1,2,3,4],0)作爲輸入,它應該給我類似於 [[3,1,2,4])的東西, [3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4], [3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4], [3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4], [3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4],[3,1,2,4], [3,1,2,4],[3,1,2,4],[3,1,2,4]] ,但它給了我[[],[],[],[],[] ,[],[],[],[],[],[],[],[],[],[],[],[] ],[],[]]。
送東西([1,2,3],nodes,0) – Benjamin
使用'search([1,2,3,4],[],0])' – mplf
當循環內部搜索調用之後立即將它們從那裏移除時,不能指望節點留在'visit_order'中。 – Sevanteri