目录
第1关:重载小于等于运算符
class Fraction:
def __init__(self,numerator = 0, denominator = 1):
if denominator == 0:
#检查分母
raise ZeroDivisionError("denominator cannot be zero")
if numerator == 0:
#检查分子
self._numerator = 0
self._denomoinator = 1
else:
if(numerator<0 and denominator>0)or(numerator>0 and denominator<0):
flag = -1
else:
flag = 1
a = abs(numerator)
b = abs(denominator)
while a%b != 0:
tempA = a
tempB = b
a = tempB
b = tempA % tempB
self._numerator = abs(numerator)//b*flag
self._denominator = abs(denominator)//b
# 请在此处添加代码 #
#根据测试用例的,重载某些方法,实现定制类#
# *************begin************#
def __lt__(self,other):
left = self._numerator * other._denominator
right = other._numerator * self._denominator
if left < right:return True
return False
def __eq__(self,other):
left = self._numerator * other._denominator
right = other._numerator * self._denominator
if left == right:return True
return False
# **************end*************#
a = int(input())
b = int(input())
frac1 = Fraction(a,b)
c = int(input())
d = int(input())
frac2 = Fraction(c,d)
print(frac1<frac2)
print(frac1==frac2)
第2关:重载加减运算符
class Fraction:
def __init__(self,numerator = 0, denominator = 1):
if denominator == 0:
raise ZeroDivisionError("denominator cannot be zero")
if numerator == 0:
self._numerator = 0
self._denomoinator = 1
else:
if(numerator<0 and denominator>0)or(numerator>0 and denominator<0):
flag = -1
else:
flag = 1
a = abs(numerator)
b = abs(denominator)
while a%b != 0:
tempA = a
tempB = b
a = tempB
b = tempA % tempB
self._numerator = abs(numerator)//b*flag
self._denominator = abs(denominator)//b
# 请在此处添加代码 #
#根据测试用例的,重载某些方法,实现定制类#
# *************begin************#
def __add__(self,other):
numerator = self._numerator * other._denominator + self._denominator * other._numerator
denominator = self._denominator * other._denominator
return Fraction(numerator,denominator)
def __sub__(self,other):
numerator = self._numerator * other._denominator - self._denominator * other._numerator
denominator = self._denominator * other._denominator
return Fraction(numerator,denominator)
def __str__(self):
return str(self._numerator)+"/"+str(self._denominator)
# **************end*************#
a = int(input())
b = int(input())
frac1 = Fraction(a,b)
c = int(input())
d = int(input())
frac2 = Fraction(c,d)
resultSUB = frac1-frac2
print(resultSUB)
resultADD = frac1+frac2
print(resultADD)