当前位置:首页 >> 脚本专栏

Python实现分数序列求和

我就废话不多说了,直接上代码吧!

#!/usr/bin/env python
# coding:UTF-8
 
 
"""
@version: python3.x
@author:曹新健
@contact: 617349013@qq.com
@software: PyCharm
@file: 1223.py
@time: 2018/12/23 20:56
"""
 
'''
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
'''
"""
#方法一
def g(n):
  if n <= 2:
    return n
  else:
    return g(n-1) + g(n-2)
sum = 0
for i in range(1,21):
  sum += g(i+1)/g(i)
print(sum)
"""
 
#方法二
numerator = 2
denominator = 1
sum = 0
while True:
  try:
    n = int(input("请输入一个整数:"))
  except ValueError:
    print("输入错误,请输入整数")
  else:
    for i in range(n):
      sum += numerator / denominator
      numerator, denominator = numerator + denominator, numerator
 
    print(sum)
    break

补充拓展:Python分数加法的实现

或多或少大家都会觉得用电脑计算器不能显示分数很麻烦,所以用Python做一个分数加法是极好的

a = input()
b = a.split(',')
 
def eu(a,b):
  if a < b:
    a, b = b, a
  r = 1
  while 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))

实际上用fractions模块可以瞬间解决问题

from fractions import Fraction
a,b = (input().split(','))
sum=Fraction(a)+Fraction(b)
print(sum)

以上这篇Python实现分数序列求和就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。