Python练习实例024

问题:有一分数序列:2/1, 3/2, 5/3, 8/5, 13/8, 21/13...求出这个数列的前20项之和。

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

# Author   : Ma Yi
# Blog     : http://www.cnblogs.com/mayi0312/
# Date     : 2020-06-19
# Name     : demo024
# Software : PyCharm
# Note     : 有一分数序列:2/1, 3/2, 5/3, 8/5, 13/8, 21/13...求出这个数列的前20项之和。


# 入口函数
if __name__ == '__main__':
    # 与斐波那契数列有关
    a, b = 1, 2
    result = 0
    temp_list = []
    for i in range(20):
        result += b / a
        temp_list.append("%s/%s" % (b, a))
        a, b = b, a + b
    print("+".join(temp_list) + "=%s" % result)

运行结果:

2/1+3/2+5/3+8/5+13/8+21/13+34/21+55/34+89/55+144/89+233/144+377/233+610/377+987/610+1597/987+2584/1597+4181/2584+6765/4181+10946/6765+17711/10946=32.66026079864164

猜你喜欢

转载自www.cnblogs.com/mayi0312/p/13161430.html