稍麻烦,讲道理觉得应该是一道甲级的25分题才对……
分类讨论思想,程序模块化才能不乱。
格式转换要趁早。
三元表达式让代码更易读。
def gcd(m, n): # 欧几里得算法
m, n = abs(m), abs(n)
if m < n:
m, n = n, m
while m % n != 0:
r = m % n
m, n = n, r
return int(n) # 最大公约数
def deal(x):#由特殊到一般
x1, x2 = list(map(int, x.split('/')))
if int(x1) == 0:
return '0'
if x1 % x2 == 0:
return '(' + str(int(x1 / x2)) + ')' if x[0] == '-' else int(x1 / x2)
n = gcd(x1, x2)
x1, x2 = int(x1 / n), int(x2 / n) # 化简
if abs(x1) <= abs(x2):
return '(' + str(x1) + '/' + str(x2) + ')' if x[0] == '-' else str(x1) + '/' + str(x2)
else:
if x[0] == '-':
return '(-' + str(int(abs(x1) // x2)) + ' ' + str(abs(x1) - int(abs(x1) // x2 * x2)) + '/' + str(x2) + ')'
else:
return str(int(x1 // x2)) + ' ' + str(x1 - int(x1 // x2 * x2)) + '/' + str(x2)
def jia(x1, x2, y1, y2):
g = gcd(x2, y2)
mu, zi = x2 * y2 / g, x1 * y2 / g + y1 * x2 / g
return result(mu, zi)
def jian(x1, x2, y1, y2):
y1 = -y1
g = gcd(x2, y2)
mu, zi = x2 * y2 / g, x1 * y2 / g + y1 * x2 / g
return result(mu, zi)
def cheng(x1, x2, y1, y2):
mu, zi = x2 * y2, x1 * y1
return result(mu, zi)
def chu(x1, x2, y1, y2):
mu, zi = x2 * y1, x1 * y2
return result(mu, zi)
def result(mu, zi):
return str(int(abs(zi))) + '/' + str(int(abs(mu))) if mu * zi >= 0 else '-' + str(int(abs(zi))) + '/' + str(int(abs(mu)))
a, b = input().split()
a1, a2 = list(map(int, a.split('/')))
b1, b2 = list(map(int, b.split('/')))
print(deal(a), '+', deal(b), '=', deal(jia(a1, a2, b1, b2)))
print(deal(a), '-', deal(b), '=', deal(jian(a1, a2, b1, b2)))
print(deal(a), '*', deal(b), '=', deal(cheng(a1, a2, b1, b2)))
print(deal(a), '/', deal(b), '=', deal(chu(a1, a2, b1, b2))) if b1 != 0 else print(deal(a), '/', deal(b), '=', 'Inf')