m0_57743728 2021-05-14 15:33 采纳率: 0%
浏览 4

[Python] Design a class ‘fractions’ so that the fr

[Python] Design a class ‘fractions’ so that the fractions can be directly added and subtracted like integers. For example, 2/1+3/5=13/5, and make sure that the numerator and denominator do not have a common factor greater than 1.(hint: overwrite __str__, __add__, __sub__ methods)…… 请问怎么确保分子分母的因数只有1呀~
  • 写回答

1条回答 默认 最新

  • ARMFUN 2024-06-21 19:36
    关注
    
    import math
    
    class Fraction:
        def __init__(self, numerator, denominator):
            if denominator == 0:
                raise ValueError("Denominator cannot be zero")
            self.numerator = numerator
            self.denominator = denominator
            self.simplify()
        
        def simplify(self):
            """Simplify the fraction by dividing both numerator and denominator by their GCD."""
            gcd = math.gcd(self.numerator, self.denominator)
            self.numerator //= gcd
            self.denominator //= gcd
        
        def __str__(self):
            return f"{self.numerator}/{self.denominator}"
        
        def __add__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
            new_denominator = self.denominator * other.denominator
            return Fraction(new_numerator, new_denominator)
        
        def __sub__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
            new_denominator = self.denominator * other.denominator
            return Fraction(new_numerator, new_denominator)
        
        def __eq__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            return (self.numerator == other.numerator) and (self.denominator == other.denominator)
    
    # Example usage
    frac1 = Fraction(2, 1)
    frac2 = Fraction(3, 5)
    print(f"{frac1} + {frac2} = {frac1 + frac2}")
    print(f"{frac1} - {frac2} = {frac1 - frac2}")
    
    
    评论

报告相同问题?