使用 self.xxxx 作为默认参数 - Python [重复]

2023-11-26

我正在尝试简化我的一个家庭作业问题并使代码变得更好一点。我正在使用的是二叉搜索树。现在我的函数中有一个Tree()查找所有元素并将它们放入列表中的类。

tree = Tree()
#insert a bunch of items into tree

然后我使用 makeList() 函数从树中获取所有节点并将它们放入列表中。 要致电makeList()功能,我做tree.makeList(tree.root)。对我来说这似乎有点重复。我已经在调用树对象了tree.so the tree.root只是浪费一点打字时间。

现在 makeList 函数是:

    def makeList(self, aNode):
        if aNode is None:
            return []
        return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)

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

第一个问题是,为什么这不起作用?
第二个问题是,有没有办法可以实现呢?正如你所看到的makeList()函数是递归的,因此我无法在函数的开头定义任何内容,否则会出现无限循环。

EDIT这是所要求的所有代码:

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 = current.rChild

            if item < parent.data:
                parent.lChild = newNode
            else:
                parent.rChild = newNode

    def inOrder(self, aNode):
        if aNode != None:
            self.inOrder(aNode.lChild)
            print aNode.data
            self.inOrder(aNode.rChild)

    def makeList(self, aNode):
        if aNode is None:
            return []
        return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)


    def isSimilar(self, n, m):
        nList = self.makeList(n.root)
        mList = self.makeList(m.root) 
        print mList == nList 

拉斯曼斯answered你的第一个问题

对于你的第二个问题,你能简单地三思而后行以避免递归吗?

def makeList(self, aNode=None):
    if aNode is None:
        aNode = self.root
    treeaslist = [aNode.data]
    if aNode.lChild:
        treeaslist.extend(self.makeList(aNode.lChild))
    if aNode.rChild:
        treeaslist.extend(self.makeList(aNode.rChild))
    return treeaslist
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 self.xxxx 作为默认参数 - Python [重复] 的相关文章

随机推荐