簡體   English   中英

Python:類聲明中的遞歸

[英]Python: recursion in Class declaration

我正在嘗試在 Python 的類聲明中實現遞歸函數。 但是,該函數似乎不接受參數。 如果我在 Class 之外聲明一個遞歸函數,它就可以工作。

[一個while循環][1]也可以解決問題。 (請參閱“遍歷值”。恕我直言,我已經在鍵盤上敲了敲頭,足以允許發布 SO 帖子。

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
    def traverse(self, node):
        print(node.data)
        if (node.next == None):
            return
        else:
            node.traverse(node.next)

            
>>> a = Node('a')
>>> b = Node('b')
>>> c = Node('c')
>>> a.next = b
>>> b.next = c
>>> Node.traverse(a)
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    Node.traverse(a)
TypeError: traverse() missing 1 required positional argument: 'node'


  [1]: https://medium.com/@kojinoshiba/data-structures-in-python-series-1-linked-lists-d9f848537b4d

一個更典型的實現是。

節點代碼

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
        
    def traverse(self):               # instance method (no 2nd argument node)
        if self:                      # check if node
            print(self.data)          # output data
            if self.next:             # check for next node
                self.next.traverse()  # recursive call to next node if any
       

測試

a = Node('a')
b = Node('b')
c = Node('c')
a.next = b
b.next = c
a.traverse()     # Note: Node.traverse(a) also works
                 # This is because
                 # When you call an instance method (e.g. traverse) from an
                 # instance object (e.g. a), Python automatically passes 
                 # that instance object as the first argument (in addition
                 # to any other arguments) to the function call
                 # Thus: a.traverse() becomes Node.traverse(a)

輸出

a
b
c

您需要使traverse成為類方法。 目前,它表示您缺少node參數,因為在Node.traverse(a)您提供了self=a而不是node=a

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None

    @classmethod # This is the only addition needed :) 
    def traverse(self, node):
        print(node.data)
        if node.next is None:
            return
        else:
            node.traverse(node.next)

Python Cookbook ,第 117 頁,你會發現這個秘訣是這個問題的更好解決方案:

class Node:
  def __init__(self, value):
    self._value = value
    self._children = []

  def __repr__(self):
    return 'Node({!r})'.format(self._value)

  def add_child(self, node):
    self._children.append(node)

  def __iter__(self):
    return iter(self._children)

  def depth_first(self):
    yield self
    for c in self:
      yield from c.depth_first()


if __name__ == '__main__':
  root = Node(0)
  child1 = Node(1)
  child2 = Node(2)
  root.add_child(child1)
  root.add_child(child2)
  child1.add_child(Node(3))
  child1.add_child(Node(4))
  child2.add_child(Node(5))
  for ch in root.depth_first():
    print(ch)

嘗試使用這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM