文章目录 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13..., 分别求出这个数列的前10项之和以及前20项之和,并打印输出,输出格式要求小数点后保留4位。 有一分数序列:2/1,
文章目录
- 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13..., 分别求出这个数列的前10项之和以及前20项之和,并打印输出,输出格式要求小数点后保留4位。
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…, 分别求出这个数列的前10项之和以及前20项之和,并打印输出,输出格式要求小数点后保留4位。
""" iterator """def fib_variant(generate_max_times):
count = 0
a, b = 2, 3
while count < generate_max_times:
yield a
a, b = b, a+b
count += 1
return "end"
def fib_variant2(generate_max_times):
count = 0
a, b = 1, 2
while count < generate_max_times:
yield a
a, b = b, a+b
count += 1
""" test the iterator: """
# for i in fib_variant(10):
# print(i)
# for i in fib_variant2(10):
# print(i)
""" calculate:sum: 2/1,3/2,5/3,8/5,13/8,21/13."""
def sum_fib_variant(bound):
count = 0
f1 = fib_variant(bound)
f2 = fib_variant2(bound)
""" range from 0(not 1) """
for i in range(0, bound):
count += next(f1)/next(f2)
# print(count)
return count
print("sum_10=%.4f" % sum_fib_variant(10))
print("sum_20=%.4f" % sum_fib_variant(20))