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

Functional recursive function with reduce

I’m given a sequence tuple(range(1,5)) and I am supposed to write a recursive function with reduce to calculate the product 1*2*3*4*5 = 24.

I don’t know how to do this recursively, I’ve tried looking here https://www.burgaud.com/foldl-foldr-python/ and understand reduce is left-fold. My none recursive implementation is simply:

def red(func, seq):
    return reduce(func, seq)

red(lambda x, y: x*y, tuple(range(1,5)))

As reduce is left fold, how can I achieve this?

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

>Solution :

To make a function recusive, you need to add a case for termination (only one element left) and the recusive call in which you make the problem smaller (go one step ahead in the sequence)

def reduce(func, seq):
    if len(seq) == 1:
        return seq[0]
    return func(seq[0], reduce(func, seq[1:]))


print(reduce(lambda x, y: x * y, tuple(range(1, 5))))

Output:

24

If you’re using python 3.10+, you should look into pattern matching for a more functional style in python.

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