python-3.x - 函数调用后我的计数器没有重置
问题描述
嘿,各位程序员,这里是 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.8, 'children': [{'name': 'CSA', 'grade': 0.5, 'children': [None, {'name': 'TA', 'grade': 0.6}]}, {'name': 'IP', 'grade': 0.99}]}))
解决方案
推荐阅读
- excel - Power Query-Excel - 有没有办法使用可以根据日期更改的状态使用过滤器或切片器?
- javascript - 我可以从我的 express 应用程序中使用 firestore npm 库吗?
- javascript - 更新和附加到 React 数组状态
- dictionary - 我在哪里可以获得英法词典数据库?
- c++ - 如何在 Windows 上使用 C++ 在特定音频设备上播放声音?
- tfs - TFS 构建过程无法提取 nuget 包
- android - Scrollview 导致自定义视图不显示
- cron - OVH - 执行 cron
- javascript - Socket IO 握手与 Postman 一起工作,但不在代码中
- anylogic - 如何改变代理的处理时间,并在延迟块期间调用它