##哈喽这里是红石小蝈
##up最近在Python里构建一个库
##代码还知道如何发到github上
##以下是Rational类部分(up萌新,有错误请指出,配色使用Py原装配色)
##代码自取
##为获得更好的观看效果,请用网页端阅读
from math import*
class Rational:
'''a rational number class instead of
python integer or floating numbers, the
base of rational functions'''
def __init__(self,num=0,den=1):
ifden == 0:
raise ZeroDivisionError('the denominator can\'t be zero')
elif notisinstance(num,(int,float)) and isinstance(den,(int,float)):
raise TypeError('the numrator and the denominator can only be numbers')
if den == 1and isinstance(num,float):
raise NotImplementedError('''you still can\'t change floating numbers into Rationals,
if u have questions please go to'''+AUTHERS_SPACE+'for help')
else:
self.num=num
self.den=den
def reduct(self):
'''make the fraction in the lowest term'''
num=int(self.num/gcd(self.num,self.den))
den=int(self.den/gcd(self.num,self.den))
self.num=num
self.den=den
##change rationals into integers and floating numbers
def __int__(self):
return self.num//self.den
def __float__(self):
return self.num/self.den
##comparing rationals with others numbers
def __eq__(self,other):
return float(self)==float(other)
def __ge__(self,other):
return float(self)>=float(other)
def __gt__(self,other):
return float(self)>float(other)
def __le__(self,other):
return float(self)<&#61;float(other)
def __lt__(self,other):
return float(self)
def __ne__(self,other):
return float(self)!&#61;float(other)
##compute rationals with numbers
def __add__(self,other):
if isinstance(other,int):
return Rational(self.num&#43;other*self.den,self.den)
elif isinstance(other,Rational) :
d&#61;self.den*other.den
n&#61;self.den*other.num&#43;self.num*other.den
a&#61;Rational(d,n)
a.reduct()
return a
def __neg__(self):
return Rational(-self.num,self.den)
def __sub__(self,other):
return self&#43;(-other)
def __rsub__(self,other):
return -(self-other)
def __mul__(self,other):
if isinstance(other,int):
a&#61;Rational(self.num*other,self.den)
a.reduct()
return a
elif isinstance(other,Rational):
a&#61;Rational(self.num*other.num,self.den*other.den)
a.reduct()
return a
def __div__(self,other):
if float(other)&#61;&#61;0:
raise ZeroDivisionError(&#39;Can\&#39;t divide by zero&#39;)
ifisinstance(other,int):
a &#61; Rational(self.num,self.den*other)
a.reduct()
return a
elif isinstance(other,Rational) :
a &#61; Rational(self.num*other.den,self.den*other.num)
a.reduct()
returna
def __rdiv__(self,other):
if float(self)&#61;&#61;0:
raise ZeroDivisionError(&#39;Can\&#39;t divide by zero&#39;)
a &#61; Rational(self.den*other,self.num)
a.reduct()
return a
def __pow__(self,other):
if other>&#61;0:
return Rational(self.num**other,self.den**other)
if other<0:
return Rational(self.den**(-other),self.num**(-other))
__rmul__&#61;__mul__
__radd__&#61;__add__
##show rationals
def __repr__(self):
if self.den&#61;&#61;1:
return str(self.num)
return&#39;(&#39;&#43;str(self.num)&#43;&#39;/&#39;&#43;str(self.den)&#43;&#39;)&#39;
##如果喜欢的话&#xff0c;不要忘记留下一个三连啊&#xff01;&#xff01;