Python reduce() 函數

Python reduce() 函數python

在調用該函數以前,先要導入該函數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個參數傳入函數執行....,最終獲得最後一個結果app

好比:reduce(lambda x, y: x + y,[1,2,3,4])執行步驟:函數

先將1,2傳入:1+2 = 3rest

再將3,3傳入:3+3 = 6code

再將6,4傳入:6+4 = 10it

最終結果爲:10io

習題

Python 一個數若是剛好等於它的因子之和,這個數就稱爲"完數"。例如6=1+2+3.編程找出 1000 之內的全部完數function

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)
相關文章
相關標籤/搜索