The number of leaf nodes and the number of layers of the book are obtained today while learning the third chapter of the book "Robot Learning Combat". An error occurred following the code code on the book:
Source:
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
Run Error:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
Getnumleafs (Mytree)
File "D:\python2.7\entropy\treePlotter.py", line, in Getnumleafs
Mumleafs + + GETNUMLEAFS (Seconddict[key])
Unboundlocalerror:local variable ' mumleafs ' referenced before assignment
After the analysis of the feeling should be a recursive reference to the problem of local variables and global variables, so the source program made a small change, added the global variable statement:
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
The correct results are obtained after running:
>>> mytree = retrievetree (1)
>>> mytree
{' No surfacing ': {0: ' No ', 1: {' flippers ': {0: {' head ': {0: ' No ', 1: ' Yes '}}, 1: ' No '}}}
>>> Getnumleafs (mytree)
4
>>>
I am using the Python2.7 version, I do not know the other version is not the problem.