[英]Issue with storing values to a list in a recursive function in Python
我正在嘗試編寫一個Python函數,該函數存儲網格上兩點之間的所有路徑。 這是原始問題,我從答案中得到啟發,並嘗試在Python中創建類似版本。
我能夠通過應用遞歸函數成功打印出所有找到的路徑,但是問題是當我需要將它們存儲在列表中時,我得到了一個空列表。 我嘗試使用全局變量和局部變量作為存儲列表,它們給出了相同的結果。 有人可以在下面的代碼中發表評論,並建議我做錯了什么嗎?
非常感謝!
import numpy as np
#initialize a matrix
grid = np.arange(0, 1225).reshape((35,35))
m = 10
n = 5
#starting point
s = (0, 0)
#target point
d = (n, m)
results = []
#a function to find the next step in the path
def next_step(x, y):
step = []
dx = [0, 1]
dy = [1, 0]
for i in range(2):
next_x = x + dx[i]
next_y = y + dy[i]
if next_x >= 0 and next_x <= n and next_y >= 0 and next_y <= m:
step.append((next_x, next_y))
return step
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
print(path)
else:
for step in next_step(s[0], s[1]):
if visited[step[0],step[1]] == False:
print_all_path(step, d, visited, path)
path.pop()
visited[s[0]][s[1]] = False
def print_path(s, d):
visited = np.zeros((35,35), dtype = bool)
path = []
print_all_path(s, d, visited, path)
print_path(s, d)
問題可能是當您追加時,您只追加了path
我懷疑您做了這樣的事情:
# global
all_lists = []
# your functions
...
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
print(path)
all_lists.append(path)
...
但是,路徑仍鏈接到原始path
變量。
您可以使用以下方法解決此問題:
all_lists.append(path + [])
這將復制列表並刪除鏈接
所以整個程序現在
import numpy as np
#initialize a matrix
grid = np.arange(0, 1225).reshape((35,35))
m = 10
n = 5
#starting point
s = (0, 0)
#target point
d = (n, m)
results = []
all_paths = []
#a function to find the next step in the path
def next_step(x, y):
step = []
dx = [0, 1]
dy = [1, 0]
for i in range(2):
next_x = x + dx[i]
next_y = y + dy[i]
if next_x >= 0 and next_x <= n and next_y >= 0 and next_y <= m:
step.append((next_x, next_y))
return step
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
all_paths.append(path + [])
#print(path)
else:
for step in next_step(s[0], s[1]):
if visited[step[0],step[1]] == False:
print_all_path(step, d, visited, path)
path.pop()
visited[s[0]][s[1]] = False
def print_path(s, d):
visited = np.zeros((35,35), dtype = bool)
path = []
print_all_path(s, d, visited, path)
print_path(s, d)
print all_paths
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.