Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining functions recursively in python

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

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

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

like image 371
splinter Avatar asked Apr 24 '26 13:04

splinter


1 Answers

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.

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)
like image 162
jasonharper Avatar answered Apr 27 '26 02:04

jasonharper