-
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
- 方法一
a,b = 1,1
s = 0
for i in range(20):
a,b = b, a+b
s += b/a
print('前二十项的和为{}'.format(s))
#前二十项的和为32.66026079864164
- 方法二
a,b = 1,1
li = []
for i in range(20):
a,b = b, a+b
li.append(b/a)
print(li)
print('前二十项的和为{}'.format(sum(li)))
**************************************************************
[2.0, 1.5, 1.6666666666666667, 1.6, 1.625, 1.6153846153846154, 1.619047619047619, 1.6176470588235294, 1.6181818181818182, 1.6179775280898876, 1.6180555555555556, 1.6180257510729614, 1.6180371352785146, 1.618032786885246, 1.618034447821682, 1.6180338134001253, 1.618034055727554, 1.6180339631667064, 1.6180339985218033, 1.618033985017358]
前二十项的和为32.66026079864164
- 方法三
from functools import reduce
a,b = 1,1
li = []
for i in range(20):
a,b = b, a+b
li.append(b/a)
s = reduce(lambda x,y:x+y, li)
print('前二十项的和为{}'.format(s))
#前二十项的和为32.66026079864164
这边出现了一个高端点的函数叫:reduce()
参考:https://www.runoob.com/python/python-func-reduce.html
-
计算阶乘和(1!+2!+3!+...+20!)
- 方法一
n = eval(input('请输入数字:'))
s = 0
for j in range(1,n+1):
a = 1#还原
for i in range(1,j+1):#计算每个n对应的阶乘
a = a*i
s += a
print(s)
#请输入数字:20
#2561327494111820313
- 方法二
采用reduce()函数
from functools import reduce
s = 0
for n in range(1,21):
li = list(range(1,n+1))
a = reduce(lambda x,y:x*y,li)
s += a
print(s)
- 方法三
def factorial(n):
if n==1:
return 1
else:
return(n*factorial(n-1))
s = 0
li = []
for n in range(1,21):
a = 0
a = factorial(n)
li.append(a)
print(sum(li))
这个是递归法
这么写也可以:
def factorial(n):
if n==1:
return 1
else:
return(n*factorial(n-1))
s = 0
for n in range(1,21):
a = 0
a = factorial(n)
s += a
print(s)
网友评论