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))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章