0
Can someone please explain to me how this python code works. I found it in a challenge and I'm clearly missing something...
>>>def func(num): >>> g=lambda x:1 if x==1 else x*g(x-1) >>> return g(num) >>>print(func(4)) The output is: 24
1 Réponse
+ 3
It is a function to find factorial...
g = lambda x: 1 if x == 1 else x*g(x-1)
here func(4) is printed
Then num == 4
And in
return g(num)
We can see that x == num
So
g(4) willl be
4 * g(3) ...(i)
now again, we have to find g(3)
which is 3 * g(2)
So (i) can be written as
4 * 3 * g(2)
Similarly for g(2)
4 * 3 * 2 * g(1)
Now x == 1 so it will return 1
So it will be
4 * 3 * 2 * 1
Which is 24
You can learn about lambda here
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2460/?ref=app