I am trying to write a lambda function to do the same program which I already implemented using a while loop, but I am not able to figure out how to correct my current program using the lambda function. As here, I want to multiply 4 with decreased value of n. For example, 3 should work like 4*3=12 and then 12*2=24, but here it's multiplying 4 always with 3 if n=3. Using a while loop, I wrote this program like below given in foo function.
It's not factorial; basically, I want to print this series for different values of n like:
n=1 ans=4,
n=2 ans=8,
n=3 ans=24,
n=4 ans=96,
n=5 ans= 480.
The logic in foo function is generating this output.
foo= lambda n: 4*n**~-n
def foo(n):
a=4
i=1
while i<=n:
a*=i
i+=1
return a
print(foo(7)) #20160
~ is a unary bitwise operator meaning NOT. ~x is equivalent to -x - 1. Let's break this down:
4*n**~-n == 4*3**~-3 == 4*3**(~-3) == 4*3**2 == 4*(3**2) == 4*9 == 36
What you want is to find 4 * factorial(n). You can import the math module to do that:
from math import factorial
def foo(n):
return 4 * factorial(n)
This would interpret to:
from math import factorial
foo = lambda n: 4*factorial(n)
The problem with the above approach is that lambdas were created to be nameless. Using a lambda when you want to use it more than once is against their intent. Just stick with the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With