4

This:

add = lambda x, y: x += y 

Gives:

SyntaxError: invalid syntax

My task is to be able to mullitply or add every number between 1-513 with 1 function and 2 lambda functions. So if you have any suggestions that'll help.

2
  • 10
    x += y is a statement, not an expression. lambdas can only contain expressions. Try lambda x, y: x+y instead. Commented Oct 15, 2018 at 4:38
  • Possible duplicate of Why doesn't print work in a lambda? Commented Oct 15, 2018 at 4:42

2 Answers 2

3

As everybody said, you should put an expression not a statement in lambda body, Maybe this will help you:

from functools import reduce add = lambda x,y: reduce(lambda i,j:i+j, range(x,y)) 

for mul:

mult = lambda x,y: reduce(lambda i,j:i*j, range(x,y)) 

or you can go without reduce, for add :

add = lambda x,y: sum(range(x,y)) 

also, you can use operator like this:

from operator import mul from functools import reduce mult = lambda x,y: reduce(mul, range(x,y), 1) 
Sign up to request clarification or add additional context in comments.

Comments

1

For continued multiplication, this works:

f = lambda n1, n2: n2 * (f(n1, n2-1) if n2 > 1 else 1) print('f(1, 5) =', f(1, 5)) 

This output:

f(1, 5) = 120 

(1 * 2 * 3 * 4 * 5 = 120)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.