2016-11-24 64 views
2

我有一個遞歸函數與數組作爲存儲路徑,當我旅行網格,從(0,0)到(x,y),我有當我在最後打印出path以跳過被定義爲「不可用」Python - 瞭解變量傳遞的範圍遞歸函數

我實現我的功能這樣

unAvailablePoint = [(1, 2), (3, 0), (0, 3), (2, 3), (0, 1)] 

def steppable(point): 
    return point not in unAvailablePoint 

def travel(x, y, path, visited): 
    if x >= 0 and y >= 0 and steppable((x, y)): 
     if (x, y) in visited: 
      return visited[(x, y)] 
     success = False 
     if (x, y) == (0, 0) or travel(x-1, y, path, visited) or travel(x, y-1, path, visited): 
      path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path 
      success = True 
     visited[(x, y)] = success 
     return success 
    return False 

path = [] 
visited = {} 
travel(3, 3, path, visited) 
print(path) //[] 

幾點,看來path仍然是空的。這不是我期望的Python新手。任何建議將是有益的

+0

那麼,你的旅行函數只返回'True' /'False',所以'path'變化停留在遞歸步驟的範圍內。 – Fejs

+0

這在Java中是不同的,它允許您按照遞歸步驟修改參數。回到軌道時,調用者應該能夠獲得傳遞給子遞歸步驟的參數的更新值? –

回答

3

嘗試添加到路徑,而不是將其初始化遞歸的每一次迭代:代替

path.append((x,y)) #the path will remain empty even after the recursive call have done some changes to the path 

path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path 

這樣,你是不是初始化列出每個迭代,所以它不會是該函數的局部變量。

+0

它的工作原理。但是爲什麼我們會重新初始化列表,因爲我們使用'path = path + [(x,y)]'? –

+1

因爲'path = path + [(x,y)]'在函數中,所以當你這樣做時,你將path作爲局部變量傳遞給travel函數。當你使用append時,你要確保路徑在函數內部沒有初始化,所以他不會是函數的局部變量。 @KesongXie –

+1

另一個解決方案:'path + = [(x,y)]' – MarianD