-1

当给出具有以下内容的边列表时,我试图在图中打印不同的节点:

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

2 回答 2

2

当我查看您插入的文本时,您似乎将制表符和空格混合为左侧空格:

这可以通过查看每一行的 repr 来确认:

'    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选项检查空格问题。

于 2012-07-15T20:01:42.433 回答
0

也为我工作。

一种可能更 Pythonic 的形式,使用 set:

def find_nodes(graph):
    return list({element
                 for edge in graph
                 for element in edge})
于 2012-07-15T19:46:20.057 回答