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.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • 10
    `x += y` is a statement, not an expression. `lambda`s can only contain expressions. Try `lambda x, y: x+y` instead. – Adam Smith Oct 15 '18 at 04:38
  • Possible duplicate of [Why doesn't print work in a lambda?](https://stackoverflow.com/questions/2970858/why-doesnt-print-work-in-a-lambda) – tripleee Oct 15 '18 at 04:42

2 Answers2

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)
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
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)

Amy Chou
  • 146
  • 5