import logging
logging.basicConfig( # 用日誌打印輸出信息
level = logging.INFO,
format = "%(asctime)s [*] %(message)s"
)
def factorialR(N):
"""遞歸函數"""
assert isinstance(N, int) and N >= 1
return 1 if N <= 1 else N * factorialR(N-1)
def factorialI(N):
"""迭代功能"""
assert isinstance(N, int) and N >= 1
product = 1
while N >= 1:
product *= N
N -= 1
return product
from functools import reduce
from operator import mul
def factorialHOF(n):
"""高階函數"""
return reduce(mul, range(1,n+1), 1)
logging.info(factorialR(5))
logging.info(factorialI(5))
logging.info(factorialHOF(5))
輸出:
2019-11-20 12:40:15,252 [*] 120
2019-11-20 12:40:15,252 [*] 120
2019-11-20 12:40:15,252 [*] 120