Python实现Pat 1088. Rational Arithmetic (20)

来源:互联网 发布:vb.net 添加控件 编辑:程序博客网 时间:2024/05/21 19:21

题目

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.

Input Specification:

Each input file contains one test case, which gives in one line the two rational numbers in the format “a1/b1 a2/b2”. The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output Specification:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is “number1 operator number2 = result”. Notice that all the rational numbers must be in their simplest form “k a/b”, where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output “Inf” as the result. It is guaranteed that all the output integers are in the range of long int.

Sample Input 1:
2/3 -4/2
Sample Output 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
Sample Input 2:
5/3 0/6
Sample Output 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

解答

from fractions import Fractiondef printFractions_kab(f):    if f==0 or f=='Inf':        print (f,end='')        return 0    else:        n=f.numerator        d=f.denominator        k=abs(n)//d        a=abs(n)%d        b=d        if n<0:            k=-k            if k==0:                a=-a        if k<0 or a<0:            print('(', end='')        if k!=0:            # pyhton2中,在结尾加个‘,’就可以使输出后不换行,例如             # print ('%d '%k), #但 pyhton3中 取消该项语法            # pyhton3中 默认end='\n',修改为end=''后使输出不换行            print ('%d'%k,end='')        if k != 0 and a!=0:            print(' ',end='')        if a!=0:            print ('%d/%d'%(a,b),end='')        if k<0 or a<0:            print(')', end='')        return 0f1,f2=[Fraction(x) for x in input().split(' ')]sum=f1+f2difference=f1-f2product=f1*f2if f2.numerator==0:    quotient='Inf'else:    quotient=f1/f2printFractions_kab(f1)print (' + ',end='')printFractions_kab(f2)print (' = ',end='')printFractions_kab(sum)print ()printFractions_kab(f1)print (' - ',end='')printFractions_kab(f2)print (' = ',end='')printFractions_kab(difference)print ()printFractions_kab(f1)print (' * ',end='')printFractions_kab(f2)print (' = ',end='')printFractions_kab(product)print ()printFractions_kab(f1)print (' / ',end='')printFractions_kab(f2)print (' = ',end='')printFractions_kab(quotient)

难得的AC

这里写图片描述