Home > database >  Functional recursive function with reduce
Functional recursive function with reduce

Time:02-11

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?

CodePudding user response:

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.

  • Related