定义计算N的阶乘的函数
1)使用循环计算阶乘
def frac(n):
r = 1
if n<=1:
if n==0 or n==1:
return 1
else:
print('n 不能小于0')
else:
for i in range(1, n+1):
r *= i
return r
print(frac(5))
print(frac(6))
print(frac(7))
120
720
5040
2)使用递归计算阶乘
def frac(n):
if n<=1:
if n==0 or n==1:
return 1
else:
print('n 不能小于0')
else:
return n * frac(n-1)
print(frac(5))
print(frac(6))
print(frac(7))
120
720
5040
3)调用reduce函数计算阶乘
说明:Python 在 functools 模块提供了 reduce() 函数,该函数使用指定函数对序列对象进行累计。
查看函数信息:
import functools
print(help(functools.reduce))
Help on built-in function reduce in module _functools:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
import functools
def fn(x, y):
return x*y
def frac(n):
if n<=1:
if n==0 or n==1:
return 1
else:
print('n 不能小于0')
else:
return functools.reduce(fn, range(1, n+1))
print(frac(5))
print(frac(6))
print(frac(7))
120
720
5040
# 使用 lambda 简写
import functools
def frac(n):
if n<=1:
if n==0 or n==1:
return 1
else:
print('n 不能小于0')
else:
return functools.reduce(lambda x, y: x*y, range(1, n+1))
print(frac(5))
print(frac(6))
print(frac(7))
120
720
5040