鱼C论坛

 找回密码
 立即注册
查看: 1604|回复: 10

python

[复制链接]
发表于 2021-2-3 21:15:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 hrh1023 于 2021-2-3 21:49 编辑
  1. class Fraction:
  2.     def __init__(self, a, b):
  3.         self.numerator = a
  4.         self.denominator = b

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

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

  9.     def __mul__(self, other):
  10.         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 而是数字啊
27d4a87c054130b6ac4a52b416f7eb2.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-2-3 21:22:52 | 显示全部楼层
  1. return int(...)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-2-3 21:33:01 | 显示全部楼层

你好
return int(self.numerator+other.numerator == self.denominator+other.denominator)
我这样输入后 最后结果变成两个0了 请问还有哪里出错了吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-3 21:59:33 | 显示全部楼层
hrh1023 发表于 2021-2-3 21:33
你好
return int(self.numerator+other.numerator == self.denominator+other.denominator)
我这样输 ...

蛤?
我这里是1和0
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-2-3 22:03:58 | 显示全部楼层
qiuyouzhi 发表于 2021-2-3 21:59
蛤?
我这里是1和0

可是答案应该要是1/4 和3/10
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-3 22:16:39 | 显示全部楼层
本帖最后由 qiuyouzhi 于 2021-2-3 22:34 编辑
hrh1023 发表于 2021-2-3 22:03
可是答案应该要是1/4 和3/10


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

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

  5.     def __init__(self, num, den = 1):
  6.         if isinstance(num, float):
  7.             self.convert(float(num), flag = True)
  8.             return
  9.         elif isinstance(num, str):
  10.             num, den = map(int, num.split('/'))
  11.         self.numerator = num
  12.         self.denominator = den
  13.         self._rof()

  14.     def convert(self, obj = None, flag = False):
  15.         """
  16.         将一个数字转换为Fraction类型
  17.         """
  18.         if isinstance(obj, int):
  19.             return Fraction(obj)
  20.         elif isinstance(obj, float):
  21.             res = str(obj).replace('.', '')
  22.             den = int("1" + ((len(res) - 1) * "0"))
  23.             fc = Fraction(int(res), den)
  24.             if not flag:
  25.                 return fc
  26.             else:
  27.                 self.numerator, self.denominator = fc.numerator, fc.denominator
  28.         else:
  29.             raise ValueError("Object's type is wrong")
  30.             

  31.     # 约分函数, reduction of a fraction
  32.     def _rof(self):
  33.         print(self.numerator, self.denominator)
  34.         gcd = math.gcd(self.numerator, self.denominator)
  35.         self.numerator //= gcd
  36.         self.denominator //= gcd
  37.         if self.numerator == self.denominator:
  38.             return 1.0

  39.     # 通分函数, reduction of fractions to a common denominator
  40.     def _rofcd(self, other):
  41.         fc1 = deepcopy(self)
  42.         fc2 = deepcopy(other)
  43.         fc1.denominator *= fc2.denominator
  44.         fc1.numerator *= fc2.denominator
  45.         fc2.denominator *= self.denominator
  46.         fc2.numerator *= self.denominator
  47.         return fc1, fc2

  48.     def __setattr__(self, key, value):
  49.         if key == "denominator" and value == 0:
  50.             raise ValueError("The denominator can't be zero")
  51.         else:
  52.             self.__dict__[key] = value

  53.     def __add__(self, other):
  54.         if isinstance(other, Fraction):
  55.             if self.denominator != other.denominator:
  56.                 fc1, fc2 = self._rofcd(other)
  57.             else:
  58.                 fc1 = deepcopy(self)            
  59.         else:
  60.             fc1 = deepcopy(self)
  61.             fc2 = self.convert(other)

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

  65.     def __sub__(self, other):
  66.         if isinstance(other, Fraction):
  67.             if self.denominator != other.denominator:
  68.                 fc1, fc2 = self._rofcd(other)
  69.                 fc1.numerator -= fc2.numerator
  70.                 fc1._rof()
  71.                 return fc1
  72.         elif isinstance(other, (float, int)):
  73.             return self.numerator / self.denominator - other

  74.     def __mul__(self, other):
  75.         if isinstance(other, Fraction):
  76.             num = self.numerator * other.numerator
  77.             den = self.denominator * other.denominator
  78.             return Fraction(num, den)
  79.         elif isinstance(other, (float, int)):
  80.             return self.numerator / self.denominator * other
  81.         
  82.     def __truediv__(self, other):
  83.         if isinstance(other, Fraction):
  84.             fc = deepcopy(other)
  85.             fc.numerator, fc.denominator = fc.denominator, fc.numerator
  86.             return self * fc
  87.         elif isinstance(other, (float, int)):
  88.             return self.numerator / self.denominator / other
  89.    
  90.     def __float__(self):
  91.         return self.numerator / self.denominator

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

  94.     __str__ = __repr__

  95. x = Fraction(1, 2)
  96. y = Fraction(3, 5)
  97. print(x * x) # should be 1 / 4, or any fraction equal to this
  98. print(x * y) # should be 3 / 10, or any fraction equal to this
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-2-3 22:28:35 | 显示全部楼层
qiuyouzhi 发表于 2021-2-3 22:16
这是我以前写过的一个简陋分数类,你可以参考一下:

谢谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-3 22:34:42 | 显示全部楼层

如果问题已解决,请设置【最佳答案】
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-3 23:40:25 | 显示全部楼层
本帖最后由 °蓝鲤歌蓝 于 2021-2-3 23:42 编辑
  1. class Fraction:
  2.     def __init__(self, a, b):
  3.         self.numerator = a
  4.         self.denominator = b

  5.     def __eq__(self, other):
  6.         return (self.numerator == other.numerator) and (
  7.             self.denominator == other.denominator
  8.         )

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

  11.     def __mul__(self, other):
  12.         return Fraction(
  13.             self.numerator * other.numerator, self.denominator * other.denominator
  14.         )
复制代码


代码稍微改一下就好了。不过没实现约数,你自己试试看。
而且你的图里问题不是两个分数相加吗? 怎么写出来却是要分数相乘啊?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-4 02:42:23 | 显示全部楼层
  1.     def __mul__(self, other):
  2.         return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
  3.     def __add__(self, other):
  4.         if self.denominator == other.denominator:
  5.             return Fraction(self.numerator + other.numerator, self.denominator)
  6.         return Fraction(self.numerator*other.denominator, self.denominator*other.denominator) + Fraction(other.numerator*self.denominator, other.denominator*self.denominator)
  7.    
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-4 12:42:55 | 显示全部楼层
本帖最后由 °蓝鲤歌蓝 于 2021-2-4 12:45 编辑
  1. class ZeroDenominatorError(ArithmeticError):
  2.     pass


  3. class Fraction:
  4.     def __init__(self, a, b):
  5.         self.numerator = a
  6.         self.denominator = b

  7.         self.__symbol = 1

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

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

  14.     # -self
  15.     def __neg__(self):
  16.         a, b = self.numerator, self.denominator
  17.         if self.__symbol:
  18.             return Fraction(a, b)
  19.         return Fraction(abs(a), abs(b))

  20.     # +self
  21.     def __pos__(self):
  22.         return self

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

  28.     def __repr__(self):
  29.         ...

  30.     __repr__ == __str__

  31.     # +
  32.     def __add__(self, other):
  33.         a, b = self.numerator, self.denominator
  34.         c, d = other.numerator, other.denominator
  35.         if a == 0:
  36.             return Fraction(c, d)
  37.         if c == 0:
  38.             return Fraction(a, b)

  39.         ad = a * d
  40.         bc = b * c
  41.         bd = b * d

  42.         return Fraction(ad + bc, bd)

  43.     # -
  44.     def __sub__(self, other):
  45.         a, b = self.numerator, self.denominator
  46.         c, d = other.numerator, other.denominator
  47.         if a == 0:
  48.             return -Fraction(c, d)
  49.         if c == 0:
  50.             return Fraction(a, b)

  51.         ad = a * d
  52.         bc = b * c
  53.         bd = b * d

  54.         return Fraction(ad + bc, bd)

  55.     # *
  56.     def __mul__(self, other):
  57.         return Fraction(
  58.             self.numerator * other.numerator, self.denominator * other.denominator
  59.         )

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

  65.         return Fraction(ad, bc)

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

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

  72.     #  !=
  73.     def __ne__(self, other) -> bool:
  74.         if isinstance(other, Fraction):
  75.             return str(self) != str(other)
  76.         return True

  77.     # ==
  78.     def __eq__(self, other):
  79.         if isinstance(other, Fraction):
  80.             return str(self) == str(other)
  81.         return False

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

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

  96.     # >
  97.     def __gt__(self, other) -> bool:
  98.         if isinstance(other, Fraction):
  99.             return float(self) > float(other)
  100.         raise TypeError(
  101.             f"'>' not supported between instances of 'Fraction' and {type(other)}"
  102.         )

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

  110.     # abs(self)
  111.     def __abs__(self):
  112.         a, b = self.numerator, self.denominator
  113.         if self.__symbol:
  114.             return Fraction(a, b)
  115.         return Fraction(-a, b)

  116.     # bool(self)
  117.     def __bool__(self):
  118.         if self.numerator == 0:
  119.             return False
  120.         return True

复制代码


这个的功能雏形差不多了,约分没实现
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-6 13:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表