Did you know that a lambda function can do recursion? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 33

Did you know that a lambda function can do recursion?

# fact for factrorial fact = lambda x: x*fact(x-1) if x>1 else 1 # When I realized this, I was very surprised.

22nd Mar 2017, 10:03 PM
Vlamir
Vlamir - avatar
4 Answers
+ 10
I have not gained enough practical experience yet and I am amazed at such things. I do not understand when the lambda function becomes defined for the fact variable. After that, it can use this variable in the definition of itself (for recursion). I thought intuitively that there should be a difference between lambda functions and named functions. I thought that for this reason lambda functions are faster than named functions. But apparently I was wrong and it is not.
22nd Mar 2017, 11:08 PM
Vlamir
Vlamir - avatar
+ 4
Ты должен заменить func(x-1) на fact(x-1) Это уже не актуально, но все равно
1st Apr 2019, 9:07 AM
Иван Дмитренко
+ 1
Honestly I do not find it surprising. However, your post is more insightful than many others I read. If I can ask, why you were surprised?
22nd Mar 2017, 10:41 PM
Alessio Meloni
Alessio Meloni - avatar
0
you must replace func with fact to make it work
19th Feb 2018, 4:04 PM
Oussama Mohamed
Oussama Mohamed - avatar