Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 带kwargs的递归函数_Python 3.x_Recursion_Keyword Argument - Fatal编程技术网

Python 3.x 带kwargs的递归函数

Python 3.x 带kwargs的递归函数,python-3.x,recursion,keyword-argument,Python 3.x,Recursion,Keyword Argument,我想要一个递归地接受kwargs的函数。我怎样才能把行李传递出去 代码示例: def recursion(a, b, **kwargs): if a == 1: print(a + b) elif a == 2: print(a + b + kwargs['name'] else: a = a/2 recursion(what to put in here?) 这将为您提供以下输出 6 Hello Wor

我想要一个递归地接受kwargs的函数。我怎样才能把行李传递出去

代码示例:

def recursion(a, b, **kwargs):
    if a == 1:
        print(a + b)
    elif a == 2: 
        print(a + b + kwargs['name']
    else:
        a = a/2
        recursion(what to put in here?)
这将为您提供以下输出

6 Hello World!
5 Hello World!
4 Hello World!
3 Hello World!
2 Hello World!
1 Hello World!

最近我遇到了一个类似的问题,我想到了以下几点:

从functools导入包装
从检查导入currentframe
def递归_kwargs(乐趣):
''通过递归调用保留关键字参数''
@包装(乐趣)
def包装(*args,**kwargs):
调用方\u name=currentframe().f\u back.f\u code.co\u name
如果呼叫者的名字很有趣。\呼叫者的名字\呼叫者:
乐趣(*args,**乐趣._u-kwargs___;)
else:#递归堆栈的顶部
有趣
乐趣(*args,**kwargs)
返回包装器
然后,您可以装饰您的功能和presto,它应该可以自己工作,而不需要传递任何Kwarg:

@recursive\u kwargs
def fib(n,代号为“垃圾邮件”,密码为“鸡蛋”):
打印(代码名、密码)
如果n==1:
返回1
返回fib(n-1)#不要通过任何kwargs
现在
fib(3)
返回
垃圾鸡蛋(3次),而
fib(3次,代号为维京人)
确实返回
维京人鸡蛋(3次)

这很方便,但是由于
@wrapps
currentframe
查找,速度很慢。以下是一些
timeit
结果:

fib:  [3.69, 3.24, 2.82, 2.57, 2.56] us # As defined above
fib2: [1.45, 1.14, 1.15, 1.08, 1.08] us # With just the @wraps (but doing nothing)
fib3: [0.58, 0.66, 0.68, 0.54, 0.48] us # Just passing the kwargs along manually
TLDR:@Harish的答案可能是实现这一点的方法,除非你不关心效率。例如,如果您处理的是浅层(恒定深度,甚至)递归堆栈,其中瓶颈是函数本身,而不是递归(也就是我在这里使用的示例)

还有,;在计算斐波那契数时,不要使用无记忆的递归(参见示例了解更多信息)

fib:  [3.69, 3.24, 2.82, 2.57, 2.56] us # As defined above
fib2: [1.45, 1.14, 1.15, 1.08, 1.08] us # With just the @wraps (but doing nothing)
fib3: [0.58, 0.66, 0.68, 0.54, 0.48] us # Just passing the kwargs along manually