zoukankan      html  css  js  c++  java
  • Python reduce() 函数

    Python reduce() 函数

    在调用该函数之前,先要导入该函数from functools import reduce

    def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
        """
        reduce(function, sequence[, initial]) -> value
        
        Apply a function of two arguments cumulatively to the items of a sequence,
        from left to right, so as to reduce the sequence to a single value.
        For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
        ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
        of the sequence in the calculation, and serves as a default when the
        sequence is empty.
        """
        pass
    

    通俗解释:reduce(function, sequence): function是一个函数,sequence是一个数据集合(元组、列表等)。先将集合里的第1,2个参数参入函数执行,再将执行结果和第3个参数传入函数执行....,最终得到最后一个结果

    比如:reduce(lambda x, y: x + y,[1,2,3,4])执行步骤:

    先将1,2传入:1+2 = 3

    再将3,3传入:3+3 = 6

    再将6,4传入:6+4 = 10

    最终结果为:10

    习题

    Python 一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出 1000 以内的所有完数

    from functools import reduce
    for i in range(2, 1001):
        l = [1]
        for j in range(2, int(i / 2 + 1)):
            if i % j == 0:
                l.append(j)
        if i == reduce(lambda x,y: x+y, l):
            print(i)
    
  • 相关阅读:
    SSL 1579——泽泽在巴西
    SSL 1644——取数字问题
    SSL 1589——火车票
    SSL 1506——打鼹鼠
    SSL 1212——大厅安排
    洛谷 1064——金明的预算方案(动态规划的背包问题)
    SSL 1463——公共子串
    SSL 1461——最大连续数列的和
    SSL 1643——最小乘车费用
    SSL 1460——最小代价问题
  • 原文地址:https://www.cnblogs.com/863652104kai/p/11826421.html
Copyright © 2011-2022 走看看