I need to define a function, that reduces a list to a single integer. The function takes two arguments. A "combiner": telling us how the list should be reduced and the list itself. The following is the demanded result:
Combines elements in the list lst using a combiner function.
As you can see, the combiner function takes two arguments.
It reduces the list to a single integer, depending on the combiner function.
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
10
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24
>>> reduce(lambda x, y: x * y, [4])
4
I struggle with the point on how to correctly define the first argument. How can I program which function should be used on the list? Or do I even need to make an If/Else-Statement here?
My intuition till now:
def reduce(combiner, lst):
plus_func = lambda x, y: x + y
mult_func = lambda x, y: x * y
if combiner == plus_func:
n = 0
for i in lst:
n += i
return n
elif combiner == x * y:
n = 1
for i in lst:
n * i
return n
How can I tell the function which lambda to apply?
>Solution :
You need to use the function (lambda) that is passed to the reduce:
def reduce(combiner, lst):
res = lst[0]
for v in lst[1:]:
res = combiner(res, i)
return n