如何解决函数调用后我的计数器未重置
嘿,程序员们,这里是Python(3)学习者。
这次我的问题是,我的变量应该跟踪二叉树中的节点数量(由字典和列表的组合表示),保留先前函数调用的数量,而我需要它重置。
我的输出是3个独立的函数调用: 0 3 7 我们可以看到第二棵树中的节点数量得以保留,并增加了第三棵树的数量。 虽然必须是: 0 3 4 我的代码:
nodes=0
def give_node(tree):
global nodes
if tree==None: #If the 'tree' begins with the value None,then there are no nodes.
nodes=0
return nodes
elif len(tree)==2: #If the dictionary has 2 items,then it's a leaf.
nodes+=1
elif len(tree)==3: #If the dictionary has 3 items,it's a parent with at least 1 child.
nodes+=1
if not(None == tree['children'][0]):
give_node(tree['children'][0])
if not(None == tree['children'][1]):
give_node(tree['children'][1])
return nodes
print(give_node(None))
print(give_node({'name': 'GAS','grade': 0.8,'children': [{'name': 'CSA','grade': 0.5},{'name': 'IP','grade': 0.99}]}))
print(give_node({'name': 'GAS','grade': 0.5,'children': [None,{'name': 'TA','grade': 0.6}]},'grade': 0.99}]}))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。