UnboundLocalError: local variable 'mumLeafs' referenced before assignment處理方法

來源:互聯網
上載者:User

今天在學習“機器人學習實戰”這本書的第三章時,擷取分葉節點的數目和書的層數。按照書上的原始碼編碼運行後出現錯誤:


原始碼:

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版本,不知道其他的版本是不是有這個毛病。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.