PAT 1081 Rational Sum python解法

1081 Rational Sum (20 分)
Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum.

Input Specification:
Each input file contains one test case. Each case starts with a positive integer N (≤100), followed in the next line N rational numbers a1/b1 a2/b2 … where all the numerators and denominators are in the range of long int. If there is a negative number, then the sign must appear in front of the numerator.

Output Specification:
For each test case, output the sum in the simplest form integer numerator/denominator where integer is the integer part of the sum, numerator < denominator, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

Sample Input 1:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24

题意:求几个分数的和,结果化为最简分数。

解题思路:
1.分数计算主要问题在于求最大公约数和最小公倍数,最大公约数可以使用辗转相除法,最小公倍数可由两数乘积/最大公倍数得到。
2.两个分数相加,先要把两个分母的最小公倍数求出来,也就是通分,相加之后再对和进行化简,也是就求分子分母的最大公约数。
3.多个数相加就是循环调用两个分数相加的函数。
4.最后对结果进行格式化输出,需要几个判断,有分子为0,分母为1,分子大于分母,以及分子为负数的情况。

n = int(input())
l = input().split()
#l = ['2/5', '4/15', '1/30', '-2/60', '8/3']
#l = ['4/3', '2/3']
#l = ['1/3', '-1/6', '1/8']
numerators = []
denominators = []
def gcd(n1,n2):#greatest common divisor
    return gcd(n2, n1 % n2) if n2 else n1
#    if n2:
#        return gcd(n2, n1 % n2)
#    else: 
#        return n1
def lcm(n1,n2):#lowest common multiple
    return n1*n2//gcd(n1,n2)
def  rational_sum(r1, r2):
    n1, d1 = map(int,r1.split('/'))
    n2, d2 = map(int,r2.split('/'))
    d3 = lcm(d1, d2)
    n3 = n1*(d3//d1) + n2*(d3//d2)
    if n3:
        gcd1 = gcd(abs(n3),d3)
        d3 = d3//gcd1
        n3 = n3//gcd1
    return str(n3)+'/'+str(d3)
s = l[0]
for i in range(1,len(l)):
    s = rational_sum(s,l[i])
#print(s)
n1, d1 = map(int,s.split('/'))
if d1 == 1:
    print(n1)
elif n1 == 0:
    print(n1)
elif abs(n1) > d1:
    if n1>0:
        print('%d %d/%d'%(n1//d1,n1%d1,d1))
    else:
        print('%d %d/%d'%((n1//d1)+1,abs(n1)%d1,d1))
else:
    print(s)

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/86563803