我写了这堂课:
class TNode(object):
def __init__(self, name):
self.name=name
self._children=[]
def add(self, c):
self._children.append(c)
def name(self):
return self.name
def children(self):
t=[]
for f in self._children:
t+=[f]
return t
def count(self, *ciao):
cnt = 1
for node in self._children:
cnt += node.count()
return cnt
def count_by_name(self, name):
cbn=1
for node in self._children:
if node.name == name:
cbn += node.count()
return cbn
现在我需要一种方法来计算树的叶子。我怎么写这个方法?
答案 0 :(得分:0)
试试这个:
def leafcounter(node):
if isinstance(node, dict):
return sum([leafcounter(node[n]) for n in node])
else:
return 1
leafcounter(tree)