小编chr*_*nze的帖子

使用self.xxxx作为默认参数 - Python

嘿大家好,我正在努力简化我的一个作业问题并使代码更好一些.我正在使用的是二叉搜索树.现在我在我的Tree()类中有一个函数,它找到所有元素并将它们放入列表中.

tree = Tree()
#insert a bunch of items into tree
Run Code Online (Sandbox Code Playgroud)

然后我使用我的makeList()函数从树中获取所有节点并将它们放在一个列表中.makeList()我打电话给这个功能tree.makeList(tree.root).对我来说,这似乎有点重复.我已经调用了树对象,tree.所以这tree.root只是浪费一点点打字.

现在makeList函数是:

    def makeList(self, aNode):
        if aNode is None:
            return []
        return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)
Run Code Online (Sandbox Code Playgroud)

我想让aNode输入一个默认参数,例如aNode = self.root(这不起作用),这样我可以运行这个函数,tree.makeList().

第一个问题是,为什么不起作用?
第二个问题是,有没有办法可以运作?正如你所看到的那样,makeList()函数是递归的,所以我无法在函数的开头定义任何东西,或者我得到一个无限循环.

编辑 以下是所有要求的代码:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.lChild = None
        self.rChild = None

class Tree(object):
    def __init__(self):
        self.root = None

    def __str__(self):
        current = self.root

    def isEmpty(self):
        if …
Run Code Online (Sandbox Code Playgroud)

python tree recursion object

52
推荐指数
2
解决办法
2万
查看次数

从二叉搜索树创建列表

我正在尝试列出二叉搜索树中的所有项目。我理解递归,但我不知道如何让它返回每个值,然后将其附加到列表中。我想创建一个调用的函数makeList(),该函数将返回我的树中所有项目的列表。我的程序中的所有函数都可以工作,除了makeList()函数,并且包含在内是为了确保每个人都理解我如何设置树的基本结构。

class Node(object):
    def __init__(self, data):
        self.data = data
        self.lChild = None
        self.rChild = None

class Tree(object):
    def __init__(self):
        self.root = None

    def __str__(self):
        current = self.root

    def isEmpty(self):
        if self.root == None:
            return True
        else:
            return False

    def insert (self, item):
        newNode = Node (item)
        current = self.root
        parent = self.root

        if self.root == None:
            self.root = newNode
        else:
            while current != None:
                parent = current
                if item < current.data:
                    current = current.lChild
                else:
                    current …
Run Code Online (Sandbox Code Playgroud)

python binary-search-tree

5
推荐指数
1
解决办法
1万
查看次数

帮助Python中的循环链接列表

我正在尝试制作一个循环的单链表.我希望能够修改我的代码以获得一个单独喜欢的列表但我遇到了一些麻烦.

对于我的链表,我有:

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = next


class LinkedList(object):
  def __init__(self):
    self.first = None

  def __str__(self):
    a = "["
    current = self.first
    while current != None:
      a += str(current.data) + ', ' 
      current = current.next
    a = a[:-2] + ']'  
    return a  

  def __iter__(self):
    current = self.first
    a = []
    while current != None:
      a += [current.data]
      current = current.next
    return iter(a)

  def __len__ (self):
    current = self.first
    a …
Run Code Online (Sandbox Code Playgroud)

python linked-list circular-list

2
推荐指数
1
解决办法
7468
查看次数