How does reduce function work?

前端 未结 9 1161
青春惊慌失措
青春惊慌失措 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: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)
    

提交回复
热议问题