三種方式的階乘


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
發佈了47 篇原創文章 · 獲贊 3 · 訪問量 7833
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章