UnboundLocalError: local variable 'mumLeafs' referenced before assignment处理方法
来源:互联网 发布:类似迅雷的软件 编辑:程序博客网 时间:2024/05/18 03:56
今天在学习“机器人学习实战”这本书的第三章时,获取叶节点的数目和书的层数。按照书上的源代码编码运行后出现错误:
源代码:
def getNumLeafs(myTree):
numLeafs = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == "dict":
numLeafs += getNumLeafs (secondDict[key])
else:
numLeafs += 1
return numLeafs
运行错误:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
getNumLeafs(myTree)
File "D:\python2.7\entropy\treePlotter.py", line 39, in getNumLeafs
mumLeafs += getNumLeafs (secondDict[key])
UnboundLocalError: local variable 'mumLeafs' referenced before assignment
经过分析感觉应该是递归引用中涉及到了局部变量与全局变量的问题,于是将源程序进行了一下小的改动,加入了全局变量的申明:
def getNumLeafs(myTree):
global numLeafs
numLeafs = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == "dict":
numLeafs += getNumLeafs (secondDict[key])
else:
numLeafs += 1
return numLeafs
运行后得到了正确的结果:
>>> myTree = retrieveTree(1)
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
>>> getNumLeafs(myTree)
4
>>>
我用的是Python2.7版本,不知道其他的版本是不是有这个毛病!
- UnboundLocalError: local variable 'mumLeafs' referenced before assignment处理方法
- Python - UnboundLocalError: local variable referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- UnboundLocalError: local variable ' ' referenced before assignment
- UnboundLocalError: local variable 'XXX' referenced before assignment
- UnboundLocalError: local variable 'sum1' referenced before assignment
- UnboundLocalError: local variable 'c' referenced before assignment
- UnboundLocalError: local variable 'epoch_logs' referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- 【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'i' referenced before assignment
- 【python】UnboundLocalError: local variable 'counter' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- python:UnboundLocalError: local variable 'l' referenced before assignment
- C#MySQL 链接
- 安卓实战之如何快速搭建app架构
- 实现定位获得信息
- 如果有人问你,GET和POST,有什么区别?你会如何回答?
- Android中多点触摸协议
- UnboundLocalError: local variable 'mumLeafs' referenced before assignment处理方法
- Android Studio V2.1.1 重要更新内容
- ThinkPHP pathinfo 模式下 url传递参数导致htim 无法加载css样式
- delphi不同单元传值问题
- 2016 年排名 Top 100 的 Java 类库
- Easyui tree 点击展开收缩
- 84. Permutations
- android studio如何修改包名
- 自定义瀑布流的布局