在一次采访中,我最近被问到了一个类似的问题:我必须构建一个递归函数来显示两个节点是否相连。我怎样才能让下面的代码工作呢?有没有办法“通过引用”传递a,b,c,这样当它们被实例化时,这在我调用check_connection时是有效的。Node是一个可变对象,所以它的行为应该像引用一样,但事实似乎并非如此,因为有一个错误:'NoneType is not iterable‘。如有任何建议,欢迎光临。
class Node():
def __init__(self, neighbours):
self.neighbours=neighbours
def return_neighbours(self):
return self.neighbours
def check_connection(first, second):
connections=first.return_neighbours()
for conection in connections:
if second in conection:
return True
else:
check_connection(conection,second)
a=None
b=None
c=None
a=Node(neighbours=[c])
b=Node(neighbours=[c])
c=Node(neighbours=[a,b])
check_connection(a,c)https://stackoverflow.com/questions/38271944
复制相似问题