Lambda challenge question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Lambda challenge question

Could somebody please try to explain how the below code works? I can’t get my head around how the output of this code is calculated to 24. Please help. def func(num): g=(lambda x:1 if x==1 else x*g(x-1)) return g(num) print (func(4)) Result: 24

24th Jan 2019, 3:09 PM
Karina Matuszek
Karina Matuszek - avatar
4 Answers
+ 12
The lambda function will return 1 if the parameter x is 1, otherwise it will keep calling itself recursively with the parameter x-1. So for x = 4, it will call g(3), g(2) and g(1). g(1) will return 1, so now the return values of the recursive function calls are multiplied and you get 1*2*3*4 = 24. The outer function func() is completely unnecessary.
24th Jan 2019, 3:28 PM
Anna
Anna - avatar
+ 6
Thank you all for your help! You guys are great!! So this is how it goes?: for x=4 4*g(4-1)=4*g(3) then for g(3) x=3 goes into ecquasion 4*3*g(3-1)=4*3*g(2) The same continues for g(2) 4*3*2*g(2-1)= 4*3*2*g(1) g(1)=1 So the result is 4*3*2*1=24
24th Jan 2019, 3:52 PM
Karina Matuszek
Karina Matuszek - avatar
+ 3
This function calculates the factorial of a given number somewhat obscurely
24th Jan 2019, 3:20 PM
Bebida Roja
Bebida Roja - avatar
+ 1
Hello Karina, Interesting puzzle you got there, let me try it out: def func(num)://definition of the "func" function that takes parameter "num". g=(lambda x:1 if x==1 else x*g(x-1))//if "x" (num parameter) is not 1 then x - 1 multiply the original num with the new num - 1 which is x and try again. return g(num) //return all the multiplications until x == 1 print (func(4))// num == 4 and x == 3 and that makes "g"= 12, but then x == 2 and "g" that could be "num" == 12, but then x - 1 == 1 and loop created by the lamba expression stops. Result: 24// it prints this because 12 * 2 == 24. I'm not sure if I'm explaining properly the technicalities if this algorithm but that's how it works. Thanks again for the puzzle.
24th Jan 2019, 3:36 PM
Roberto Guisarre
Roberto Guisarre - avatar