您好,欢迎来到纷纭教育。
搜索
您的当前位置:首页python默认采用_使用self.xxxx作为默认参数-Python

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

来源:纷纭教育

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

#insert a bunch of items into tree

然后使用makeList()函数从树中获取所有节点并将它们放入列表中。

要调用makeList()函数,我需要tree.makeList(tree.root)。对我来说这似乎有点重复。我已经用tree.调用了tree对象,所以tree.root只是浪费了一点输入。

现在makeList函数是:def makeList(self, aNode):

if aNode is None:

return []

return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)

我想让阳极输入成为一个默认参数,比如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 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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- fenyunshixun.cn 版权所有 湘ICP备2023022495号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务