第1关:重载小于等于运算符
任务描述
本关任务:对有理数类Fraction,重载小于等于运算符,实现有理数的相应运算。
相关知识
为了完成本关任务,你需要掌握:1.小于等于运算对应的特殊方法,2.重写该方法。
编程要求
根据提示,在右侧编辑器补充代码,实现需要的输出内容。
测试说明
平台会对你编写的代码进行测试:
测试输入: 1 2 2 4 预期输出: False True
测试输入: 6 9 4 8 预期输出: True False
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关:重载加减运算符
任务描述
本关任务:对有理数类Fraction,重载加减运算符,实现有理数的相应运算。
相关知识
为了完成本关任务,你需要掌握:1.小于等于运算对应的特殊方法,2.输出格式控制的特殊方法__repr__。
编程要求
根据提示,在右侧编辑器补充代码,实现需要的输出内容。
测试说明
平台会对你编写的代码进行测试:
测试输入: 3 4 2 3 预期输出: 1/12 17/12
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"{}/{}".format(self._numerator,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)