Create a Fraction class and overload the comparison operators ( < , > , == , >= , <= ) to allow direct comparison between Fraction objects
时间: 2024-09-20 16:16:02 浏览: 51
Direct bandgap germanium-on-silicon inferred from 5.7% <100> uniaxial tensile strain [Invited]
为了创建一个`Fraction`类,我们首先需要定义类的基本结构,包括分子(numerator)和分母(denominator),以及相关的比较方法。这里是一个简单的实现示例:
```python
class Fraction:
def __init__(self, numerator, denominator):
if denominator == 0:
raise ValueError("Denominator cannot be zero.")
self.numerator = numerator
self.denominator = abs(denominator)
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def reduce(self):
gcd = math.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
# Overload comparison operators
def __lt__(self, other):
return self.numerator * other.denominator < other.numerator * self.denominator
def __gt__(self, other):
return self.numerator * other.denominator > other.numerator * self.denominator
def __eq__(self, other):
return self.numerator * other.denominator == other.numerator * self.denominator
def __ge__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return not self.__gt__(other)
def __add__(self, other):
# ... implement addition here
def __sub__(self, other):
# ... implement subtraction here
# Add more methods as needed, like __mul__, __truediv__
```
在这个例子中,`__lt__`, `__gt__`, `__eq__`, `__ge__`, 和 `__le__` 方法分别实现了小于、大于、等于、大于等于和小于等于的比较。注意,这只是一个基础版本,实际的`__add__` 和 `__sub__` 方法还需要实现加法和减法操作。
使用这个`Fraction`类时,可以直接对两个分数对象进行比较,例如:
```python
frac1 = Fraction(3, 4)
frac2 = Fraction(7, 8)
print(frac1 < frac2) # True or False depending on the values
```
阅读全文