Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: building a reduce function with lambda

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading