python:用 reduce 函数计算阶乘

编写 compute_factorial.py 如下

# -*- coding: utf-8 -*-
""" 计算阶乘 factorial """
import sys
from functools import reduce
#help(reduce)

if len(sys.argv) ==2:
    n = int(sys.argv[1])
else:
    print('usage: python compute_factorial.py n ')
    sys.exit(1)

#n = 30
factorial = reduce(lambda x,y: x*y, range(1,n+1))
print(f"{n}!= {factorial}")

运行 python compute_factorial.py 30

请参阅:Python 中reduce()与lambda函数详解

编写检验程序 test_factorial.py 如下

# -*- coding: utf-8 -*-
""" 计算阶乘 factorial """

n = 30
factorial = 1
for i in range(2, n+1):
    factorial *= i
print(f"{n}!= {factorial}")

你可能感兴趣的:(python,python)