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