简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM