2012-07-15 98 views
-1

我想給邊緣的列表與以下時打印的不同節點圖:Python:爲什麼這個列表中的一個元素沒有被打印?

def find_nodes(graph): 
    # get the distinct nodes from the edges 
    nodes = [] 
    l = len(graph) 
    for i in range(l): 
     edge = graph[i] 
     n1 = edge[0] 
     n2 = edge[1] 
     if n1 not in nodes: 
      nodes.append(n1) 
     if n2 not in nodes: 
      nodes.append(n2) 
    return nodes 

graph = ((1,2),(2,3), (3,1)) 
print find_nodes(graph) 

但我只得到(1,2)如何我失去了3

+4

它爲我打印'[1,2,3]'。 – 2012-07-15 19:36:26

+0

同樣在這裏:http://ideone.com/NhyFb – 2012-07-15 19:37:33

+0

使用Windows命令提示符......這可能是相關的嗎? – algorithmicCoder 2012-07-15 19:38:54

回答

2

當我看着你插入的文本,它看起來像你的混合製表符和空格的左側空白:

這可以通過查看每一行的再版得到證實:

' def find_nodes(graph):' 
'  # get the distinct nodes from the edges' 
'  nodes = []' 
'  l = len(graph)' 
'  for i in range(l):' 
'  \tedge = graph[i]' 
'  \tn1 = edge[0]' 
'  \tn2 = edge[1]' 
'  \tif n1 not in nodes:' 
'  \t\tnodes.append(n1)' 
'  \tif n2 not in nodes:' 
'  \t\tnodes.append(n2)' 
' \treturn nodes' 

這可能會導致不被縮進你認爲他們是水平線條。下面是我得到的結果從複製並粘貼您的輸入到控制檯:

>>> s = """ 
...  def find_nodes(graph): 
...   # get the distinct nodes from the edges 
...   nodes = [] 
...   l = len(graph) 
...   for i in range(l): 
...    edge = graph[i] 
...    n1 = edge[0] 
...    n2 = edge[1] 
...    if n1 not in nodes: 
...      nodes.append(n1) 
...    if n2 not in nodes: 
...      nodes.append(n2) 
...    return nodes 
...  
...  graph = ((1,2),(2,3), (3,1)) 
...  print find_nodes(graph) 
... 
... """ 

在我看來像return nodes線將過早執行。將代碼寫入文件並使用python -tt選項檢查空白問題。

+0

剛剛添加這個作爲答案...確實返回沒有正確縮進...哦蟒蛇..我很快會習慣你:) – algorithmicCoder 2012-07-15 20:09:40

+1

你應該確保你確定使用友好的Python編輯器,該編輯器使用四空間製表符進行縮進。其他任何事情都會導致頭痛。 – DSM 2012-07-15 20:10:56

0

也適用於我。

一個可能更Python的形式,採用集:

def find_nodes(graph): 
    return list({element 
       for edge in graph 
       for element in edge}) 
+0

仍然沒有打印最後的節點!..它看起來像我的循環停止後的第一個邊緣..不知道爲什麼 – algorithmicCoder 2012-07-15 19:51:13

+0

如果您使用Windows提示符,也許你打字輸入之前,你應該?聽起來令人困惑... – heltonbiker 2012-07-15 19:52:30

相關問題