The title
This problem requires programming to calculate the sum, difference, product and quotient of two rational numbers.
Input format: Input two fractional rational numbers in a row in the format a1/ B1, A2 / B2, where the numerator and denominator are all integers in the range of integers. The negative sign can only appear before the numerator, and the denominator is not 0.
Output format: Output the sum, difference, product and quotient of the two rational numbers in 4 lines in the order of the rational number 1 operator rational number 2 = result. Note that each rational number output must be the simplest form of the rational number k a/b, where K is the integer part and a/b is the simplest fraction part; If it is negative, parentheses must be added; If the denominator of the division is 0, Inf is printed. The problem ensures that the correct output contains no integers beyond the integer range.
Input example 1: no blank line at the end Output Example 1: Two-thirds of + (2) = (1/3) two-thirds - two thirds two-thirds (2) = 2 * (2) = (1/3) two-thirds/(2) = (1/3) at the end of the empty line input sample 2:0/6 5/3 when the end no empty line output sample 2: 1 2/3 + 0 = 1 2/3 1 2/3-0 = 1 2/3 1 2/3 x 0 = 0 1 2/3/0 = Inf There is no empty line at the endCopy the code
Their thinking
inputArr = input().split()
# inputArr = "2/3 -4/2".split()
from fractions import Fraction
A1, A2 = map(int, inputArr[0].split("/"))
B1, B2 = map(int, inputArr[1].split("/"))
f1 = Fraction(A1, A2)
f2 = Fraction(B1, B2)
def format1(num):
if '/' not in str(num) or abs(num)<1:
if num<0:
num = '('+ str(num)+')'
return num
else:
n1, n2 = map(int, str(abs(num)).split('/'))
if num < 0:
res = '(-' + str(n1//n2) + ' ' + str(n1%n2)+'/'+str(n2)+')'
else:
res = str(n1 // n2) + ' ' + str(n1 % n2) + '/' + str(n2)
return res
print('{} + {} = {}'.format(format1(f1), format1(f2), format1(f1+f2)))
print('{} - {} = {}'.format(format1(f1), format1(f2), format1(f1-f2)))
print('{} * {} = {}'.format(format1(f1), format1(f2), format1(f1*f2)))
if f2 == 0:
print("{} / {} = {}".format(format1(f1), format1(f2), "Inf"))
else:
print("{} / {} = {}".format(format1(f1), format1(f2), format1(f1/f2)))
Copy the code