Python計算階乘的三種方法


# 遞歸
def func(n):
    if n == 0 or n == 1:
        return 1
    else:
        return (n * func(n - 1))


# reduce函數 + lambda函數
from functools import reduce
def fact(n):
    return reduce(lambda a, b: a * b, range(1, n + 1))


# reduce函數 + operator模塊 mul函數
from functools import reduce
from operator import mul


def fact_operator(n):
    return reduce(mul, range(1, n + 1))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章