How does reduce function work?

前端 未结 9 1114
青春惊慌失措
青春惊慌失措 2020-12-01 04:25

As far as I understand, the reduce function takes a list l and a function f. Then, it calls the function f on first two elements of th

相关标签:
9条回答
  • 2020-12-01 05:00

    You could also implement factorial using reduce.

    def factorial(n):
      return(reduce(lambda x,y:x*y,range(n+1)[1:]))
    
    0 讨论(0)
  • 2020-12-01 05:02

    The other answers are great. I'll simply add an illustrated example that I find pretty good to understand reduce():

    >>> reduce(lambda x,y: x+y, [47,11,42,13])
    113
    

    will be computed as follows:

    (Source) (mirror)

    0 讨论(0)
  • 2020-12-01 05:07

    Reduce executes the function in parameter#1 successively through the values provided by the iterator in parameter#2

    print '-------------- Example: Reduce(x + y) --------------'
    
    def add(x,y): return x+y
    x = 5
    y = 10
    
    import functools
    tot = functools.reduce(add, range(5, 10))
    print 'reduce('+str(x)+','+str(y)+')=' ,tot
    
    def myreduce(a,b):
        tot = 0
        for i in range(a,b):
            tot = tot+i
            print i,tot
        print 'myreduce('+str(a)+','+str(b)+')=' ,tot
    
    myreduce(x,y)
    
    print '-------------- Example: Reduce(x * y) --------------'
    
    def add(x,y): return x*y
    x = 5
    y = 10
    
    import functools
    tot = functools.reduce(add, range(5, 10))
    print 'reduce('+str(x)+','+str(y)+')=' ,tot
    
    def myreduce(a,b):
        tot = 1
        for i in range(a,b):
            tot = tot * i
            print i,tot
        print 'myreduce('+str(a)+','+str(b)+')=' ,tot
    
    myreduce(x,y)
    
    0 讨论(0)
提交回复
热议问题