PAT甲级 Rational Sum(20) python实现 解题思路及注意事项

时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序 

题目描述

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

输入描述:

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.

输出描述:

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.

输入例子:

5
2/5 4/15 1/30 -2/60 8/3

输出例子:

3 1/3

注意事项:

 1.分子能被分母整除,则直接输出整除结果

 2.分子小于分母时,直接输出分子/分母最简形式

 3.分子为0时,结果为0,而不是0/分母


def yue(a,b):
    #约分
    if a<b:
        a,b=b,a
    r=2
    for i in range(abs(b)):
        if a%r==0 and b%r==0:
            a=a/r
            b=b/r
        else:
            r+=1
    return int(a),int(b)

N=int(input())
number=[x for x in input().split(" ")]
numerator=[]                        #分子集合
denominator=[]                      #分母集合
mulDeno=1                           #所有分母乘积
for i in range(N):
    num=number[i].split("/")
    a=num[0]
    b=num[1]
    numerator.append(int(a))
    denominator.append(int(b))
    mulDeno*=int(b)

sum=0
for i in range(N):
    sum+=mulDeno/denominator[i]*numerator[i]
if sum%mulDeno==0:
    print(int(sum/mulDeno))
else:
    count = 0
    if sum < 0:
        sum = abs(sum)
        while sum > mulDeno:
            sum -= mulDeno
            count += 1
        mulDeno, sum = yue(int(sum), int(mulDeno))
        sum=-sum
    else:
        while sum > mulDeno:
            sum -= mulDeno
            count += 1
        mulDeno, sum = yue(int(sum), int(mulDeno))
    if count == 0:
        if sum == 0:
            print(0)
        else:
            print(str(sum) + "/" + str(mulDeno))
    else:
        print(str(count) + " " + str(sum) + "/" + str(mulDeno))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值