I will stop talking nonsense, just go to the code!
#! /usr/bin/env python
# coding:UTF-8"""
@ version: python3.x
@ author:Cao Xinjian
@ contact:[email protected]
@ software: PyCharm
@ file:1223.py
@ time:2018/12/2320:56"""
'''
There is a sequence of scores: 2/1,3/2,5/3,8/5,13/8,21/13...Find the sum of the first 20 terms of this sequence.
'''
"""
# method one
def g(n):if n <=2:return n
else:returng(n-1)+g(n-2)
sum =0for i inrange(1,21):
sum +=g(i+1)/g(i)print(sum)"""
# Method Two
numerator =2
denominator =1
sum =0while True:try:
n =int(input("Please enter an integer:"))
except ValueError:print("Input error, please enter an integer")else:for i inrange(n):
sum += numerator / denominator
numerator, denominator = numerator + denominator, numerator
print(sum)break
Supplementary extension: Implementation of Python score addition
More or less everyone will find it troublesome to use a computer calculator to display scores, so it is excellent to use Python to add scores
a =input()
b = a.split(',')
def eu(a,b):if a < b:
a, b = b, a
r =1while r !=0:
r = a % b
a = b
b = r
return a
num1 = b[0].split('/')
num2 = b[1].split('/')
sum1 =int(num1[0])*int(num2[1])+int(num2[0])*int(num1[1])
sum2 =int(num1[1])*int(num2[1])
GCD =eu(sum1,sum2)
c =int(sum1/GCD)
d =int(sum2/GCD)if c%d ==0:print(int(c/d))else:print(str(c)+'/'+str(d))
In fact, the fractions module can solve the problem instantly
from fractions import Fraction
a,b =(input().split(','))
sum=Fraction(a)+Fraction(b)print(sum)
The above Python implementation of the sum of score sequences is all the content shared by the editor, I hope to give you a reference.
Recommended Posts