gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:29:47 25 4
gpt4 key购买 nike

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

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

然后我使用我的 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)

我想让 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 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

关于python - 使用 self.xxxx 作为默认参数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5555449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com