求階乘是寫程式時的經典練習,以前都用 C 寫,這次改用 Python,重點放在熟悉 lambda 與 reduce 這兩個函式。
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
def test_factorial_reduce():
"""使用 reduce 函式"""
time_begin = time.clock()
print reduce(lambda x, y: x * y, range(1, long(raw_input("please input a number ( > 0):"))))
print "Use time: %s" % (time.clock() - time_begin)
return;
def test_factorial_math():
"""使用 math 標準庫"""
import math
time_begin = time.clock()
print math.factorial(long(raw_input("please input a number ( > 0):")))
print "Use time: %s" % (time.clock() - time_begin)
if __name__ == '__main__':
print '*' * 50 + "Use reduce" + '*' * 50
test_factorial_reduce()
print '*' * 50 + "Use math api" + '*' * 50
test_factorial_math()
實測(輸入 50):reduce 版本花約 3.32 秒,math 模組版本約 3.70 秒,兩者結果一致。
手冊的描述是:lambda 建立的是一個匿名 inline 函式,由單一運算式構成,呼叫時才求值,語法為 lambda [arguments]: expression。
關鍵差別在於 lambda 是一個「運算式」,而 def 是一個「語句」。因此 lambda 可以直接寫在函式呼叫的參數位置,def 不行。我們的 lambda x, y: x*y 完全等價於:
def my_func(x, y):
return x * y
手冊描述為 reduce(function, iterable[, initializer]):把雙參數函式由左至右累積套用到序列的項目上,將整個序列化為單一值。例如 reduce(lambda x, y: x+y, [1,2,3,4,5]) 的計算過程是 ((((1+2)+3)+4)+5)。左參數 x 是累積值,右參數 y 是序列取出的下一項;若提供 initializer,它會被放在序列之前作為初始值。
換個寫法就一目了然了:
def my_func(x, y):
print 'x = %d, y = %d' % (x, y)
return x * y
print reduce(my_func, range(1, long(raw_input("please input a number ( > 0):"))))
輸入 50 時,輸出會像這樣:
please input a number ( > 0):50 x = 1, y = 2 x = 2, y = 3 x = 6, y = 4 x = 24, y = 5 x = 120, y = 6 ... x = 12413915592536072670862289047373375038521486354677760000000000, y = 49 608281864034267560872252163321295376887552831379210240000000000
可以清楚看到每一輪的 x 都是上一輪的乘積,y 則依序取 2 到 49,這正是「用函式對序列逐項歸約」的具體樣貌。
在較新的 Python 版本中,reduce 已被移到 functools 模組,需要 from functools import reduce;range 也改為預設回傳延遲物件。上面這段範例是 Python 2 的寫法,理解精神即可,實作時記得依版本調整。若只是要求階乘,直接用 math.factorial 永遠是最省事、也最不容易出錯的選擇。