python2.7练习小例子(二十三)
23):题目:求1+2!+3!+...+20!的和。
程序分析:此程序只是把累加变成了累乘。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
n = 0
s = 0
t = 1
for n in range(1,21):
t *= n
s += t
print '1! + 2! + 3! + ... + 20! = %d' % s
#!/usr/bin/python
# -*- coding: UTF-8 -*-
s = 0
l = range(1,21)
def op(x):
r = 1
for i in range(1,x + 1):
r *= i
return r
s = sum(map(op,l))
print '1! + 2! + 3! + ... + 20! = %d' % s
以上实例输出结果为:
1! + 2! + 3! + ... + 20! = 2561327494111820313
#!/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)
#!/usr/bin/python
s = 1
t = []
for i in range(1,21):
s *= i
t.append(s)
print(sum(t)-1)
#!/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)
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)
#!/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)
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))
使用两个递归函数实现,其中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))
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)
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)
这次的小例子,主要看的是程序分析能力。如果感觉不错的话,请多多点赞支持哦。。。
原文链接:https://blog.csdn.net/luyaran/article/details/80064388