在python中递归定义函数 [英] Defining functions recursively in python

查看:49
本文介绍了在python中递归定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对lambda函数有一个简单的问题.我想做一个循环,其中每个迭代都基于前一次迭代的lambda函数定义一个新的lambda函数.

I have a simple question about lambda functions. I want to do a loop, in which every iteration defines a new lambda function based on a lambda function from the previous iteration.

f = lambda x: x**2
j=0
J=2
while j<J:
    f2 = lambda x: 0.5*f(x)
    f = f2
    j+=1

我期望f(3)的结果为2.25 = 0.5 * 0.5 * 3 ** 2.但是,出现以下错误:

I expect the result of f(3) to be 2.25 = 0.5*0.5*3**2. However, I get the following error:

RecursionError: maximum recursion depth exceeded

我认为可以像这样灵活地使用lambda函数.我想有一种正确执行此操作的已知pythonic方法?

I thought lambda functions can be used flexibly like this. I suppose there is a known pythonic way of how to do this properly?

推荐答案

在调用lambda时,会在上查找lambda中的名称 f -此时它指向lambda本身,因此是无限递归.

The name f inside your lambda is looked up at the time the lambda is called - at which point it refers to the lambda itself, thus the infinite recursion.

在特定时间捕获值的通常习惯是将其设置为lambda的默认参数,该参数在定义时进行评估:

The usual idiom for capturing a value at a particular moment in time is to make it a default parameter of the lambda, which gets evaluated at definition time:

    f2 = lambda x, f=f: 0.5*f(x)

这篇关于在python中递归定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆