我要为一个自定义的系统树类实现一个长度方法,这样我们就可以在它上面调用len(TreeObject)。树的长度由它有多少个叶子来定义。叶子表示节点没有子节点。'self.children‘等于该节点的子节点的元组(节点,权重)列表。我非常接近我相信:
def __len__(self):
# everytime it reaches the base case I should add 1
if self.isLeaf():
print('base case - reached leaf!')
return 1
for t,w in self.children:
print('not leaf so sent through loop')
numLeaves = len(t)
return numLeaves代码到达if语句的次数是正确的,例如,如果长度为3,它将分别输出“base case - reached!”3次。我只需要一种将它们加在一起并将其存储在变量中的方法。
发布于 2013-02-12 06:04:32
确实非常接近。您只是覆盖了numLeaves,而不是对它们求和:
numLeaves = 0
for t,w in self.children:
print('not leaf so sent through loop')
numLeaves += len(t)它也可以以不同的方式实现:
sum(len(t) for (t,w) in self.children)https://stackoverflow.com/questions/14821630
复制相似问题