How does Python Lambda recursion expression work?

rec_fn = lambda: 10==11 or rec_fn()
rec_fn()

I am new to Python and trying to understand how lambda expressions work. Can someone explain how this recursion works? I can understand that 10 == 11 will be "false" and that rec_fn will be called again and again recursively.

But what I can't get is apparently a new way to write a lambda expression.

what happened to lambda x: x+y, where is the parameter "x" included in the unnamed function?

Also why

rec_fn() = lambda: .... // a syntax error
rec_fn = lambda: .... //syntactically correct - WHY?

What is rec_fn? Is this a function or variable?

+3
source share
5 answers

. , . rec_fn(), . -, rec_fn. , ( Python , , ). (), " , ". , , , , , .

def func1():
   print "func1"

func2 = func1

func2()       # prints "func1"

, .

func3 = lambda x: x+1

, func2 = func1, - . ; - .

Lambdas , lambda: 3 - , 3, lambda x, y: x+y - , .

or, . , or , True, , True . , if not 10==11: rec_fn(). , and , , False, , False , .

+4

- x() - . . ? ( , 42 = lambda: ....)

, ( lambda) ( rec_fn) .

, () -- :

# just for example, not really useful as it is unless you like to eat CPU
def rec_fn():
  return 10 == 11 or rec_fn()

rec_fn()

lambda - , .

rec_fn - (, /). rec_fn , (). (, ), , .

0
  rec_fn = lambda: 10==11 or rec_fn()
  rec_fn()

, ,

rec_fn = lambda x: 10==11 or rec_fn(x)
x = ...
rec_fn(x)

you'r rec_fn(), , , x

rec_fn() = lambda: .... // a syntax error

rec_fn() ( ) . , -.

rec_fn = lambda: .... //syntactically correct - WHY?

rec_fn , ( , )

0
rec_fn = lambda: 10==11 or rec_fn()
rec_fn()

. rec_fn . - , rec_fn. , . rec_fn, . , , . 10==11 or rec_fn(). or, . 10==11 False, , ( ) rec_fn. rec_fn (), (). . :

def rec_fn():
    return 10==11 or rec_fn()

Lambdas , . lambda: ... , ", ".

, (, , lambdas) . , , .

rec_fn = lambda: ...

, rec_fn. , rec_fn(), .

rec_fn() = lambda: ...

, - rec_fn().

:

def rec_fn2(): # here you may use the parens with the name to indicate it takes no arguments
    ...        # unlike in the lambda assignment above

.

0

This is perhaps a more understandable example of recursion, the factorial lambda version:

fact = lambda x: 1 if x == 0 else x*fact(x-1)
prin(fact(10))

Conclusion:

3628800

Remember the Python recursion limit.

Usage example or like this if ..else:

print 1 or 'a'
print 'a' or False
print False or True or 0/9
fact_or = lambda x: x == 0 and 1 or x * fact_or(x-1)
print fact_or(10)
0
source

Source: https://habr.com/ru/post/1769075/


All Articles