我正在學習Python的遞歸。我定義了一個鏈表,其中每個節點有item
,next
和level
。我想寫一個遞歸從頭部的水平與0設置爲尾,1,2 ...在Python中使用遞歸調用方法
class LinkNode(object):
"""A node in a linked list."""
def __init__(self, item, next=None):
"""(LinkNode, object, LinkNode) -> NoneType
Initialize this node to store item and have next and level 0.
"""
self.item = item
self.left = next
self.level = 0 # the level of the link
def set_level(self, level):
"""(LinkNode, int) -> NoneType
Set the level attribute of every node in the list
for example: first node is 0, second is 1, third is 3...
"""
if self is None:
pass
else:
self.level = level
levle = level + 1
self.set_level(self.next, level)
但是當我運行它,我得到了以下錯誤:
File "C:\Program Files\Wing IDE 101
4.1\src\debug\tserver\_sandbox.py", line 29, in <module> File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py",
line 21, in set_level builtins.TypeError: set_level() takes exactly 2
positional arguments (3 given)
遞歸調用有什麼問題嗎?
您需要'self.next.set_level(level)'。當你有'an_object.method(arg1,...)'時,這被隱式轉換爲解釋你錯誤的'AClass.method(an_object,arg1,...)'。 – dmg 2013-03-03 18:57:02
這也意味着'自己不是無' – Eric 2013-03-03 19:02:03
是的,檢查應該是'如果self.next不是無' – dmg 2013-03-03 19:05:47