[Python](PAT)1088 Rational Arithmetic (20 分)
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
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
題目大意
給定兩個分數,進行分數的加減乘除四則運算
分析
使用Fraction類例項化分數。定義一個change函式轉換分數的變現形式。
Fraction的使用方法 戳這裡
python實現
from fractions import Fraction
def change(a):
if a > 0:
if int(a) == a:
sa = str(int(a))
elif a> 1:
sa ='{} {}/{}'.format(int(a),(a-int(a)).numerator,(a-int(a)).denominator)
else:
sa = '{}/{}'.format(a.numerator,a.denominator)
elif a== 0:
sa = '0'
else:
if int(a) == a:
sa = '({})'.format(int(a))
elif a > -1:
sa = '({}/{})'.format(a.numerator,a.denominator)
else:
sa = '({} {}/{})'.format(int(a), abs((a-int(a)).numerator),(a-int(a)).denominator)
return sa
def main():
line = input().split(" ")
a = Fraction(line[0])
b = Fraction(line[1])
print(change(a),'+',change(b),'=',change(a+b))
print(change(a),'-',change(b),'=',change(a-b))
print(change(a),'*',change(b),'=',change(a*b))
if b == 0:
print(change(a),'/',change(b),'=','Inf')
else:
print(change(a),'/',change(b),'=',change(a/b))
if __name__ == "__main__":
main()