# 有理数
class Rational():
@staticmethod
def __gcd(m, n):
if n == 0:
m, n = n, m
while m != 0:
m, n = n % m, m
return n
def __init__(self, num, den = 1):
if not isinstance(num, int) or not isinstance(den, int):
raise TypeError
if den == 0:
raise ZeroDivisionError
sign = 1
if num < 0:
num, sign = -num, -sign
if den < 0:
den, sign = -num, -sign
g = Rational.__gcd(num, den)
self.__num = sign * (num // g)
self.__den = den // g
def den(self):
return self.__den
def num(self):
return self.__num
def __add__(self, another):
den = self.__den * another.den()
num = (self.__num * another.den() + self.__den * another.num())
return (Rational(num, den))
def __mul__(self, another):
return Rational(self.__num * another.num(), self.__den * another.den())
def __sub__(self, another):
den = self.__den * another.den()
num = (self.__num * another.den() - self.__den * another.num())
return Rational(num, den)
def __floordiv__(self, another):
if another.num() == 0:
raise ZeroDivisionError
return Rational(self.__num * another.den(), self.__den * another.num())
def __eq__(self, another):
return self.__num * another.den() == self.__den * another.num()
def __lt__(self, another):
return self.__num * another.den() < self.__den * another.num()
def __gt__(self, another):
return self.__num * another.den() > self.__den * another.num()
def __ne__(self, another):
return self.__num * another.den() != self.__den * another.num()
def __le__(self, another):
return self.__num * another.den() <= self.__den * another.num()
def __ge__(self, another):
return self.__num * another.den() >= self.__den * another.num()
def __str__(self):
return str(self.__num) + '/' + str(self.__den)
r1 = Rational(3, 15)
r2= Rational(5, 15)
print(r1, r2)
print(r1 + r2)
print(r1 - r2)
print(r1 >= r2)
print(r1 <= r2)
有理数
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...