计算前n个自然数的阶乘之和1!+2!+3!+...+n!的值。(用5种不同的方法实现)
内置函数2种
from math import factorial(2种)
from functools import reduce+from operator import mul(1种)
# 方法一
import math
n = int(input("请输入一个数字:"))
sum = 0
for i in range(1, n + 1):
sum += math.factorial(i)
print(f"前{n}个自然数的阶乘之和是{sum}")
# 方法二
from functools import reduce
n = int(input("请输入一个正整数:"))
lst = []
for i in range(1, n + 1):
num = reduce(lambda x, y: x * y, range(1, i + 1))
lst.append(num)
sum = reduce(lambda x, y: x + y, lst)
print(f"前{n}个自然数的阶乘之和是{sum}")
# 方法三
from functools import reduce
from operator import mul
n = int(input("请输入一个正整数:"))
sum_1 = 0
for i in range(1, n + 1):
num = reduce(mul, range(1, i + 1))
sum_1 = operator.add(sum_1, num)
print(f"前{n}个自然数的阶乘之和是{sum_1}")
# 方法四
n = int(input("请输入一个正整数:"))
a = 1
sum = 0
for i in range(1, n+1):
a *= i
sum += a
print(f"前{n}个自然数的阶乘之和是{sum}")
# 方法五
import math
n = int(input("请输入一个正整数:"))
sum = 0
for i in range(1, n + 1):
sum += math.factorial(i-1)*i
print(sum)
# 方法六
import numpy as np
n = int(input("请输入一个正整数:"))
lst = list(range(1, n + 1))
sum = 0
for i in range(1, n+1):
sum += np.prod(lst[0:i])
print(f"前{n}个自然数的阶乘之和是{sum}")
演示结果: