gpt4 book ai didi

python - 将自身数据传递给递归函数

转载 作者:太空宇宙 更新时间:2023-11-03 19:37:57 26 4
gpt4 key购买 nike

我正在尝试设置一个函数来执行类似的操作

   def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None):

当前节点作为根开始,然后我们在方法中将其更改为不同的节点并再次递归调用它。

但是,我无法让“currentNode=getRoot()”工作。如果我尝试调用函数 getRoot() (如上所述),它会说我没有给它所有必需的变量,但如果我尝试调用 self.getRoot() ,它会提示 self 是一个 undefined variable 。有没有一种方法可以在调用此方法时无需指定根来执行此操作?

编辑:此方法的基本情况已经

if currentNode == None:

所以用它来设置根目录是行不通的

最佳答案

同时arg=None是非提供参数的惯用 Python 哨兵值,它必须None 。例如,在 Lua 中,惯用的非提供参数是一个空表。我们实际上可以将其应用到本例中:

class Foo:
sentinel = {}
def bar(self, arg=sentinel):
if arg is self.sentinel:
print "You didn't supply an argument!"
else:
print "The argument was", arg

f = Foo()
f.bar(123)
f.bar()
f.bar(None)
f.bar({})

输出:

The argument was 123You didn't supply an argument!The argument was NoneThe argument was {}

这适用于除显式传递 Foo.sentinel 之外的任何情况。 ,因为Foo.sentinel保证有一个唯一的地址——意思是x is Foo.sentinel仅当 x Foo.sentinel 时才为 true :) 因此,由于我们在 Foo.sentinel 周围创建了闭包,只有一个对象可以产生歧义情况,而且永远不会被意外使用。

关于python - 将自身数据传递给递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2443264/

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