Python 练习实例25
题目:求1+2!+3!+...+20!的和。
程序分析:此程序只是把累加变成了累乘。
方法一
方法二
以上实例输出结果为:
1! + 2! + 3! + ... + 20! = 2561327494111820313
题目:求1+2!+3!+...+20!的和。
程序分析:此程序只是把累加变成了累乘。
以上实例输出结果为:
1! + 2! + 3! + ... + 20! = 2561327494111820313
小白
358***[email protected]
参考解法:
#!/usr/bin/python # -*- coding: UTF-8 -*- s=0 def fact(n): if n==1: return 1 return n*fact(n-1) for n in range(1,21): a=fact(n) s+=a print(s)
小白
358***[email protected]
健健
459***[email protected]
参考方案:
#!/usr/bin/python s = 1 t = [] for i in range(1,21): s *= i t.append(s) print(sum(t)-1)
健健
459***[email protected]
习惯乌龙茶
rea***[email protected]
参考解法:
#!/usr/bin/python # -*- coding: UTF-8 -*- sum1=0 for each in range(1,21): sum2=1 while each>1: sum2=sum2*each each-=1 sum1+=sum2 print(sum1)
习惯乌龙茶
rea***[email protected]
等一个人
252***[email protected]
Python3 参考解法:
#!/usr/bin/env python3 s = 0 for i in range(1, 21): r = 1 for j in range(1, i+1): r *= j s += r print(s)
等一个人
252***[email protected]
丸子酱
105***[email protected]
参考方法:
#!/usr/bin/python3
n=int(input("Enter a number:"))
s=0
def cal(n):
pro=1
for i in range(1,n+1):
pro=pro*i
return pro
for i in range(1,n+1):
if i!=n:
print("%d! + "%i,end='')
else:
print("%d! = "%i,end='')
s=s+cal(i)
print(s)
丸子酱
105***[email protected]
Think-dfrent
iwa***[email protected]
python3 测试实例:使用两个递归函数实现,其中jie()生成阶乘,sum()对阶乘求和
#!/usr/bin/env python3
def jie(n):
if n==1:
return 1
else:
return n*jie(n-1)
def sum(n):
if n==1:
return jie(1)
else:
return jie(n)+sum(n-1)
#a=int(input("请输入一个正整数:\n"))
#print(sum(a))
print(sum(20))
Think-dfrent
iwa***[email protected]
Think-dfrent
iwa***[email protected]
使用两个递归函数实现,其中jie()生成阶乘,sum()对阶乘求和
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def jie(n):
if n==1:
return 1
else:
return n*jie(n-1)
def sum(n):
if n==1:
return jie(1)
else:
return jie(n)+sum(n-1)
#a=int(input("请输入一个正整数:\n"))
#print(sum(a))
print(sum(20))
Think-dfrent
iwa***[email protected]
colinshi
col***[email protected]
Python3 下测试:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import math
def jc(m):
l=[]
for n in range(1,m+1):
l.append(math.factorial(n)) #阶乘函数。
if m>1:
print('{}!+'.format(n),end='')
m -= 1
else:
print('{}!='.format(n),end='')
print(sum(l))
if __name__=='__main__':
jc(20)
colinshi
col***[email protected]
抠脚丫子闻
ora***[email protected]
Python3下的实现
#python 3 from functools import reduce a = 0 for n in range(1, 21): a += reduce(lambda x, y: x * y, range(1, n + 1)) print(a)
抠脚丫子闻
ora***[email protected]