hrh1023 发表于 2021-2-3 21:15:48

python

本帖最后由 hrh1023 于 2021-2-3 21:49 编辑

class Fraction:
    def __init__(self, a, b):
      self.numerator = a
      self.denominator = b

    def __eq__(self, other):
      return(self.numerator * other.denominator == self.denominator * other.numerator)

    def __str__(self):
      return str(self.numerator) + " / " + str(self.denominator)

    def __mul__(self, other):
      return int(self.numerator * other.denominator == self.denominator * other.numerator)


x = Fraction(1, 2)
y = Fraction(3, 5)
print(x * x) # should be 1 / 4, or any fraction equal to this
print(x * y) # should be 3 / 10, or any fraction equal to this






怎么样才可以让那个最后验算的结果不是false 而是数字啊

qiuyouzhi 发表于 2021-2-3 21:22:52

return int(...)

hrh1023 发表于 2021-2-3 21:33:01

qiuyouzhi 发表于 2021-2-3 21:22


你好
return int(self.numerator+other.numerator == self.denominator+other.denominator)
我这样输入后 最后结果变成两个0了 请问还有哪里出错了吗

qiuyouzhi 发表于 2021-2-3 21:59:33

hrh1023 发表于 2021-2-3 21:33
你好
return int(self.numerator+other.numerator == self.denominator+other.denominator)
我这样输 ...

蛤?
我这里是1和0

hrh1023 发表于 2021-2-3 22:03:58

qiuyouzhi 发表于 2021-2-3 21:59
蛤?
我这里是1和0

可是答案应该要是1/4 和3/10

qiuyouzhi 发表于 2021-2-3 22:16:39

本帖最后由 qiuyouzhi 于 2021-2-3 22:34 编辑

hrh1023 发表于 2021-2-3 22:03
可是答案应该要是1/4 和3/10

这是我以前写过的一个简陋分数类,你可以参考一下:
import math
from copy import deepcopy

class Fraction:
    """一个简单的分数类,模仿fractions.Fraction"""

    def __init__(self, num, den = 1):
      if isinstance(num, float):
            self.convert(float(num), flag = True)
            return
      elif isinstance(num, str):
            num, den = map(int, num.split('/'))
      self.numerator = num
      self.denominator = den
      self._rof()

    def convert(self, obj = None, flag = False):
      """
      将一个数字转换为Fraction类型
      """
      if isinstance(obj, int):
            return Fraction(obj)
      elif isinstance(obj, float):
            res = str(obj).replace('.', '')
            den = int("1" + ((len(res) - 1) * "0"))
            fc = Fraction(int(res), den)
            if not flag:
                return fc
            else:
                self.numerator, self.denominator = fc.numerator, fc.denominator
      else:
            raise ValueError("Object's type is wrong")
            

    # 约分函数, reduction of a fraction
    def _rof(self):
      print(self.numerator, self.denominator)
      gcd = math.gcd(self.numerator, self.denominator)
      self.numerator //= gcd
      self.denominator //= gcd
      if self.numerator == self.denominator:
            return 1.0

    # 通分函数, reduction of fractions to a common denominator
    def _rofcd(self, other):
      fc1 = deepcopy(self)
      fc2 = deepcopy(other)
      fc1.denominator *= fc2.denominator
      fc1.numerator *= fc2.denominator
      fc2.denominator *= self.denominator
      fc2.numerator *= self.denominator
      return fc1, fc2

    def __setattr__(self, key, value):
      if key == "denominator" and value == 0:
            raise ValueError("The denominator can't be zero")
      else:
            self.__dict__ = value

    def __add__(self, other):
      if isinstance(other, Fraction):
            if self.denominator != other.denominator:
                fc1, fc2 = self._rofcd(other)
            else:
                fc1 = deepcopy(self)            
      else:
            fc1 = deepcopy(self)
            fc2 = self.convert(other)

      fc1.numerator += fc2.numerator
      k = fc1._rof()
      return k if k else fc1

    def __sub__(self, other):
      if isinstance(other, Fraction):
            if self.denominator != other.denominator:
                fc1, fc2 = self._rofcd(other)
                fc1.numerator -= fc2.numerator
                fc1._rof()
                return fc1
      elif isinstance(other, (float, int)):
            return self.numerator / self.denominator - other

    def __mul__(self, other):
      if isinstance(other, Fraction):
            num = self.numerator * other.numerator
            den = self.denominator * other.denominator
            return Fraction(num, den)
      elif isinstance(other, (float, int)):
            return self.numerator / self.denominator * other
      
    def __truediv__(self, other):
      if isinstance(other, Fraction):
            fc = deepcopy(other)
            fc.numerator, fc.denominator = fc.denominator, fc.numerator
            return self * fc
      elif isinstance(other, (float, int)):
            return self.numerator / self.denominator / other
   
    def __float__(self):
      return self.numerator / self.denominator

    def __repr__(self):
      return f"Fraction({self.numerator}, {self.denominator})"

    __str__ = __repr__

x = Fraction(1, 2)
y = Fraction(3, 5)
print(x * x) # should be 1 / 4, or any fraction equal to this
print(x * y) # should be 3 / 10, or any fraction equal to this

hrh1023 发表于 2021-2-3 22:28:35

qiuyouzhi 发表于 2021-2-3 22:16
这是我以前写过的一个简陋分数类,你可以参考一下:

谢谢

qiuyouzhi 发表于 2021-2-3 22:34:42

hrh1023 发表于 2021-2-3 22:28
谢谢

如果问题已解决,请设置【最佳答案】

°蓝鲤歌蓝 发表于 2021-2-3 23:40:25

本帖最后由 °蓝鲤歌蓝 于 2021-2-3 23:42 编辑

class Fraction:
    def __init__(self, a, b):
      self.numerator = a
      self.denominator = b

    def __eq__(self, other):
      return (self.numerator == other.numerator) and (
            self.denominator == other.denominator
      )

    def __str__(self):
      return str(self.numerator) + "/" + str(self.denominator)

    def __mul__(self, other):
      return Fraction(
            self.numerator * other.numerator, self.denominator * other.denominator
      )


代码稍微改一下就好了。不过没实现约数,你自己试试看。
而且你的图里问题不是两个分数相加吗? 怎么写出来却是要分数相乘啊?

kogawananari 发表于 2021-2-4 02:42:23

    def __mul__(self, other):
      return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
    def __add__(self, other):
      if self.denominator == other.denominator:
            return Fraction(self.numerator + other.numerator, self.denominator)
      return Fraction(self.numerator*other.denominator, self.denominator*other.denominator) + Fraction(other.numerator*self.denominator, other.denominator*self.denominator)
   

°蓝鲤歌蓝 发表于 2021-2-4 12:42:55

本帖最后由 °蓝鲤歌蓝 于 2021-2-4 12:45 编辑

class ZeroDenominatorError(ArithmeticError):
    pass


class Fraction:
    def __init__(self, a, b):
      self.numerator = a
      self.denominator = b

      self.__symbol = 1

      if a * b < 0:
            self.__symbol = 0

    def __setattr(self, name, value):
      if name == "denominator" and value == 0:
            raise ZeroDenominatorError("denominator by zero")
      return super().__setattr(self, name, value)

    # -self
    def __neg__(self):
      a, b = self.numerator, self.denominator
      if self.__symbol:
            return Fraction(a, b)
      return Fraction(abs(a), abs(b))

    # +self
    def __pos__(self):
      return self

    def __str__(self):
      a, b = self.numerator, self.denominator
      if a == 0:
            return "0"
      return "-" * abs(self.__symbol - 1) + f"{abs(a)}/{abs(b)}"

    def __repr__(self):
      ...

    __repr__ == __str__

    # +
    def __add__(self, other):
      a, b = self.numerator, self.denominator
      c, d = other.numerator, other.denominator
      if a == 0:
            return Fraction(c, d)
      if c == 0:
            return Fraction(a, b)

      ad = a * d
      bc = b * c
      bd = b * d

      return Fraction(ad + bc, bd)

    # -
    def __sub__(self, other):
      a, b = self.numerator, self.denominator
      c, d = other.numerator, other.denominator
      if a == 0:
            return -Fraction(c, d)
      if c == 0:
            return Fraction(a, b)

      ad = a * d
      bc = b * c
      bd = b * d

      return Fraction(ad + bc, bd)

    # *
    def __mul__(self, other):
      return Fraction(
            self.numerator * other.numerator, self.denominator * other.denominator
      )

    # /
    def __truediv__(self, other):
      if other.numerator == 0:
            raise ZeroDivisionError("division by zero")
      ad, bc = self.numerator * other.denominator, self.denominator * other.numerator

      return Fraction(ad, bc)

    # int(self)
    def __int__(self):
      return int(self.numerator / self.denominator)

    # float(self)
    def __float__(self):
      return self.numerator / self.denominator

    #!=
    def __ne__(self, other) -> bool:
      if isinstance(other, Fraction):
            return str(self) != str(other)
      return True

    # ==
    def __eq__(self, other):
      if isinstance(other, Fraction):
            return str(self) == str(other)
      return False

    # <
    def __lt__(self, other) -> bool:
      if isinstance(other, Fraction):
            return float(self) < float(other)
      raise TypeError(
            f"'<' not supported between instances of 'Fraction' and {type(other)}"
      )

    # <=
    def __le__(self, other) -> bool:
      if isinstance(other, Fraction):
            return float(self) <= float(other)
      raise TypeError(
            f"'<=' not supported between instances of 'Fraction' and {type(other)}"
      )

    # >
    def __gt__(self, other) -> bool:
      if isinstance(other, Fraction):
            return float(self) > float(other)
      raise TypeError(
            f"'>' not supported between instances of 'Fraction' and {type(other)}"
      )

    # >=
    def __ge__(self, other) -> bool:
      if isinstance(other, Fraction):
            return float(self) >= float(other)
      raise TypeError(
            f"'>=' not supported between instances of 'Fraction' and {type(other)}"
      )

    # abs(self)
    def __abs__(self):
      a, b = self.numerator, self.denominator
      if self.__symbol:
            return Fraction(a, b)
      return Fraction(-a, b)

    # bool(self)
    def __bool__(self):
      if self.numerator == 0:
            return False
      return True



这个的功能雏形差不多了,约分没实现
页: [1]
查看完整版本: python