"Python3 Exercise 019" has a fractional sequence: 2/1,3/2,5/3,8/5,13/8,21/13. Find out the sum of the first 20 items of this series.

Source: Internet
Author: User

After a fraction of the numerator = numerator of the previous fraction + denominator, the denominator of the next fraction = the numerator of the previous fraction, the cycle is 20 times the result. Note that the numerator is a and the denominator is B, although a = a + B,

But at this point A has become a+b, so to re-assign the value of the time, it is (a+b)-B to be equal to the original denominator B, so re-assignment should be written as a-a

Method One

From fractionsImport fraction


def Fibonacci (N):
A, B =1,2
res = [1]
i =1
While i < n:
A, B = b, a+b
Res.append (a)
i + = 1
Else:
return Res

result = Fibonacci (21)

Sum_result = SUM ([Fraction (i[0], i[1]) for I in Zip (result[1:], result[0:- 1]))
Print (Sum_result)


Method Two
from fractions import Fraction sum = 0 a, b = 2 , 1 for i in range ( 20 ):      sum = sum + Fraction(a / b)      a = a + b      b = a - b print ( sum )Method Three sum = 0 a, b = 2 , 1 for i in range ( 20 ):      sum = sum + a / b      a = a + b      b = a - b print ( sum )

"Python3 Exercise 019" has a fractional sequence: 2/1,3/2,5/3,8/5,13/8,21/13. Find out the sum of the first 20 items of this series.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.