阶乘的表示方法(day4)
一、初级的for循环计算阶乘:def factorial(n):
result = n
for i in range(1, n):
result *= i
return result
temp = int(input('请输入一个正整数:'))
res = factorial(temp)
print('%d的阶乘:%d' % (temp, res)).
二、用递归函数简化的阶乘计算:
def factorial1(n):
if n == 1:
return 1
else:
return n * factorial1(n - 1)
temp = int(input('请输入一个正整数:'))
res = factorial1(temp)
print('%d的阶乘:%d' % (temp, res))
三、用functools.reduce结合lambda计算阶乘:
import functools
temp = int(input('请输入一个正整数:'))
res = functools.reduce(lambda x, y: x * y, range(1,temp + 1))
print('%d的阶乘:%d' % (temp, res))
页:
[1]