Python按功能打印列表,但结果为“无”

时间:2019-12-23 17:33:25

标签: python-3.x function class

请查看以下代码:

from collections import defaultdict 
stat1 = []
stat2 = []

class Graph:

    def __init__(self): 
        self.graph = defaultdict(list)

    def addEdge(self,u,v): 
        self.graph[u].append(v)

    def BFS(self, s): 

        global stat1
        global stat2

        if s in self.graph:
            if s not in stat1:
                stat1.append(s)
            else:
                pass
        else:
            return []


        for i in range(len(self.graph[s])):
            if self.graph[s][i] in stat1 or self.graph[s][i] in stat2:
                pass
            else:
                stat1.append(self.graph[s][i])
            i = i + 1

        if s in stat2:
            pass
        else:
            stat2.append(s)
            del stat1[0]


        if stat1 != []:
            self.BFS(stat1[0])

        else:
            print (stat2)
            stat1 = []
            stat2 = []

然后我通过以下代码检查此代码:

g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

g.BFS(2)
print('-------------------------------------------------------------')
print(g.BFS(2))

这是输出。

[2, 0, 3, 1]
-------------------------------------------------------------
[2, 0, 3, 1]
None

我想知道为什么print(g.BFS(2))g.BFS(2)的输出不同? 如果我需要将print(g.BFS(2))的输出与g.BFS(2)相同怎么办? (没有None)?

根据一些相关的问题,我已经尝试将BFS和DFS函数的最后几行更改为以下几行:

if stat1 != []:
    self.BFS(stat1[0])
else:
#   print (stat2)
    ans = stat2
    stat1 = []
    stat2 = []
    return ans

但是,测试代码的结果为None,没有ans列表。

任何建议将不胜感激!

0 个答案:

没有答案