1 #!/usr/bib/env python
2 #-*- coding:utf-8 -*-
3
4 """
5 ADT Rational: #定义有理数的抽象数据类型6 Rational(self, int num, int den) #构造有理数num/den7 +(self, Rational r2) #求出本对象加r2的结果8 -(self, Rational r2) #求出本对象减r2的结果9 *(self, Rational r2) #求出本对象乘以r2的结果10 /(self, Rational r2) #求出本对象除以r2的结果11 num(self) #取出本对象的分子12 den(self) #取出本对象的分母13 int(self) #取整14 float(self) #取浮点数15 ==(self,Rational r2)16 !=(self,Rational r2)17 >(self,Rational r2)18 =(self,Rational r2)20 >=(self,Rational r2)21 """
22
23 classRational(object):24 __slots__ = (‘_num‘, ‘_den‘)25
26 @staticmethod27 def_gcd(m,n):28 while 1:29 temp = n %m30 if temp ==0:31 returnm32 else:33 n =m34 m =temp35
36 def __init__(self, num, den=1):37 if not isinstance(num, int) or notisinstance(num, int):38 raiseTypeError39 if den ==0:40 raiseZeroDivisionError41 sign = 1
42 if num <0:43 num, sign = -num, -sign44 if den <0:45 den, sign = -den, -sign46 g =Rational._gcd(num, den)47 self._num = sign*(num//g)48 self._den = den//g49
50 #float
51 x = self._num /self._den52 self._num =x.as_integer_ratio()[0]53 self._den = x.as_integer_ratio()[1]54
55 def __add__(self, other):56 den = self._den *other._den57 num = self._den * other._num + self._num *other._den58 returnRational(num, den)59
60 def __sub__(self, other):61 den = self._den *other._den62 num = self._num * other._den - self._den *other._num63 returnRational(num, den)64
65 def __mul__(self, other):66 den = self._den *other._den67 num = self._num *other._num68 returnRational(num, den)69
70 def __floordiv__(self, other):71 den = self._den *other._num72 num = self._num *other._den73 returnRational(num, den)74
75 def __int__(self):76 return self._num //self._den77
78 def __float__(self):79 return self._num /self._den80
81 def __eq__(self, other):82 return self._num * other._den == self._den *other._num83
84 def __ne__(self, other):85 return self._num * other._den != self._den *other._num86
87 def __lt__(self, other):88 return self._num * other._den < self._den *other._num89
90 def __le__(self, other):91 return self._num * other._den <= self._den *other._num92
93 def __gt__(self, other):94 return self._num * other._den > self._den *other._num95
96 def __ge__(self, other):97 return self._num * other._den >= self._den *other._num98
99
100 def __str__(self):101 return str(self._num) + "/" +str(self._den)102
103 def print(self):104 print(self._num, "/", self._den)105
106 defnum(self):107 returnself._num108 defden(self):109 returnself._den110
111 if __name__ == ‘__main__‘:112 a = Rational(10,5)113 b = Rational(1,1000000)114 print(a)115 print(b)116 print("==")117 print(a+b)118 print(a!=b)119 print(int(a))120 print(int(b))