2015-12-23 16 views
0

我試圖調用此功能(僅第一線事項):表被視爲一個元組

def find_path(graph, start, end, path=[]): 
    path = path + [start] 
    if start == end: 
     return path 
    if not graph.has_key(start): 
     return None 
    for node in graph[start]: 
     if node not in path: 
      newpath = find_path(graph, node, end, path) 
      if newpath: return newpath 
    return None 

這樣的:

find_path(self.neighbors, (4,4), (0,4)) 

,但我總是得到這個錯誤:

path = path + [start] 
TypeError: can only concatenate tuple (not "list") to tuple 

我知道,我不能改變一個元組,但我認爲path是一個列表,當我檢查它是鍵入它說的元組,怎麼回事?你有什麼建議來解決它?謝謝

+2

是'find_path'函數或方法?你用'self.neighbors'作爲第一個參數來調用它,所以你是否缺少'def find_path(self,...)'? –

+3

對於使用可變默認參數也非常謹慎。這應該在這種情況下工作,但它是容易搞砸的那些「陷阱」之一(例如,如果你的第一行是'path.append(start)'!) –

+0

感謝@AdamSmith,那真的是問題,我感覺很尷尬,我沒有注意到 –

回答

3

正如在評論中證實,該代碼的情況下的樣子:

class SomeClass: 

    ... 
    def find_path(graph, start, end, path=[]): 
     ... 

在這種情況下,當你調用它,它通過

find_path(graph=self, start=self.neighbors, end=(4,4), path=(0,4)) 

您需要定義與該方法簽名

def find_path(self, graph, start, end, path=[]) 

關於可變默認參數的說明:是ve當你決定使用它們時,請小心。它適用於這種情況,因爲您首先要做的第一件事是在path = path + [start]的方法範圍內重新定義path,但是如果您的第一行是其他方面相同的path.append(start),那麼您的方法將是很難很難調試。

默認參數的作用域與它們所屬的函數的作用域相同,因此突變一個參數會在將來每次調用該函數時改變它。正因爲如此「疑難雜症」的共同成語是:

def find_path(..., path=None): 
    if path is None: 
     path = [] 

或(等效地,但不太常見)

path = [] if path is None else path 
0

您需要查看作爲「路徑」參數傳遞的內容。我懷疑你的代碼以某種方式給它一個元組。

>>> (4,4) + [] 
Traceback (most recent call last): 
    File "<pyshell#13>", line 1, in <module> 
    (4,4) + [] 
TypeError: can only concatenate tuple (not "list") to tuple 
>>> [] + (4,4) 
Traceback (most recent call last): 
    File "<pyshell#14>", line 1, in <module> 
    [] + (4,4) 
TypeError: can only concatenate list (not "tuple") to list 

堆棧跟蹤你得到對應於第一種情況下,在「路徑」是一個元組和[開始]時,正如所料,含元組的列表。

+0

那麼他也定義了一個列表文字,所以我們知道第二個元素是一個按照定義的列表。沒有時間當'[something]'不是一個列表 –

+1

那麼,現在你提到它... –

相關問題