如何用Python的迭代器或生成器计算数列前n项之和?

2026-06-11 01:161阅读0评论SEO资讯
  • 内容介绍
  • 相关推荐

本文共计434个文字,预计阅读时间需要2分钟。

如何用Python的迭代器或生成器计算数列前n项之和?

文章目录+

一、分数序列概述:

1.分数序列的定义

2.分数序列的性质

如何用Python的迭代器或生成器计算数列前n项之和?

二、分数序列的应用:

1.分数序列在数学中的应用

2.分数序列在生活中的应用

三、分数序列的前10项之和及前20项之和:

1.分数序列前10项之和的计算

2.分数序列前20项之和的计算

四、分数序列的输出:

1.分数序列的打印格式要求

2.分数序列的输出示例


文章目录

  • ​​有一分数序列: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))


本文共计434个文字,预计阅读时间需要2分钟。

如何用Python的迭代器或生成器计算数列前n项之和?

文章目录+

一、分数序列概述:

1.分数序列的定义

2.分数序列的性质

如何用Python的迭代器或生成器计算数列前n项之和?

二、分数序列的应用:

1.分数序列在数学中的应用

2.分数序列在生活中的应用

三、分数序列的前10项之和及前20项之和:

1.分数序列前10项之和的计算

2.分数序列前20项之和的计算

四、分数序列的输出:

1.分数序列的打印格式要求

2.分数序列的输出示例


文章目录

  • ​​有一分数序列: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))