2016-05-15 108 views
-1

我有任務爲Dijkstra的算法編寫類。雖然我不能編輯的Dijkstra類:NoneType對象不可迭代錯誤

class Dijkstra(): 
# initialize with a string containing the root and a 
# weighted edge list 
def __init__(self, in_string): 
    self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string) 
    self.nodes = [Node(i) for i in range(self.nnodes)] 
    self.nodes[self.root].key = 0 
    self.heap = MinHeap(self.nodes) 
# the input is expected to be a string 
# consisting of the number of nodes 
# and a root followed by 
# vertex pairs with a non-negative weight 
def convert_to_adj_list(self, in_string): 
    nnodes, root, edges = in_string.split(';') 
    root = int(root) 
    nnodes = int(nnodes) 
    adj_list = {} 
    edges = [ map(int,wedge.split()) for wedge in edges.split(',')] 
    for u,v,w in edges: 
     (adj_list.setdefault(u,[])).append((v,w)) 
    for u in range(nnodes): 
     adj_list.setdefault(u,[]) 

這是我的問題:

string = '3; 0; 1 2 8, 2 0 5, 1 0 8, 2 1 3' 
print(Dijkstra(string)) 
Traceback (most recent call last): 
    File "<pyshell#321>", line 1, in <module> 
    print(Dijkstra(string)) 
    File "C:\Users\TheDude\Downloads\dijkstra.py", line 71, in __init__ 
    self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string) 
TypeError: 'NoneType' object is not iterable 

難道我給你append的返回值?我該如何解決它不W/o編輯 class Djikstra() 坦克供閱讀。

+0

'convert_to_adj_list'回報'None',因爲你沒有用一個return語句爲它供給。 – miradulo

+0

你應該從'convert_to_adj_list'得到一個返回值,所以將'return adj_list'添加到'convert_to_adj_list'定義的末尾。 –

+0

所以如果我不設置返回值,任何函數都會返回None? 我必須使用Dijkstra類,所以我需要聯繫老師來解決這個問題。 – TheDude

回答

2

爲了分配

self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string) 

工作,convert_to_adj_list必須返回三個值中的一個元組,待分解爲這三個變量。但是,您的方法不會返回任何內容(因此隱式返回None)。更改convert_to_adj_list方法是這樣的,那麼它應該工作:

def convert_to_adj_list(self, in_string): 
    ... your code ... 
    return root, nnodes, adj_list 
+0

謝謝tobias! – TheDude

相關問題