I am trying to implement the function below into one line of lambda code.
JavaScript
x
7
1
def fac(num):
2
num = int(num)
3
if num > 1:
4
return num * fac(num - 1)
5
else:
6
return 1
7
I have constructed a lambda statement, but I keep getting syntax error:
JavaScript
1
2
1
z = lambda z: if (z > 1) z * (z-1) else 1
2
Advertisement
Answer
First of all, you can’t refer to a global name z
when there is a local variable (the parameter) by the same name.
Thus, we will declare a lambda statement called func
and use the ternary
operator in the good way.
JavaScript
1
2
1
func = lambda z: z * func(z-1) if (z > 1) else 1
2
Output
JavaScript
1
3
1
> func(5)
2
120
3