3

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
1
  • 3
    Why not from math import factorial; foo = lambda n: 4 * factorial(n)? Even better, define a function. Named lambda's are against their purpose. Commented Jun 21, 2016 at 2:12

1 Answer 1

4

~ 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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, actually my program is not to find factorial. It will generate numbers like as given above in question statement
Try out my function. It is indeed factorial. You will find that all test cases pass.
for n=5, your function will generate 120 while my function will generate 480. its just i don't know how to do it using lambda
My function generates 480. Try it.
The simple fact is that lambdas cannot do while loops. You need to find a new way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.