python - 以公制前缀作为对象的减法
问题描述
我试图用前缀作为对象减去。
这是我的代码
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
centim = self.cm - other.cm
meter = (self.m - other.m) - abs(centim/100)
if meter < 1:
centim = m*100
meter = 0
return Prefix(meter, cm)
我试图以一种产生负厘米值的方式减去并从仪表对象中取 1m 以实现这一点
Prefix(2, 20) - Prefix(1, 30) == Prefix(0, 90)
解决方案
首先,请记住,对于给定的长度,百位右侧的所有内容都进入cm
,并且它或其左侧的所有内容都除以 100,然后进入m
。
鉴于此,我们可以将问题改写为将两个Prefix
对象都转换为它们的全长,在那里执行计算,然后Prefix
从结果中创建一个新对象:
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
self_length = self.m * 100 + self.cm
other_length = other.m * 100 + other.cm
result_length = self_length - other_length
result_m, result_cm = divmod(result_length, 100)
return Prefix(result_m, result_cm)
result = Prefix(2, 20) - Prefix(1, 30)
print(result.m, result.cm)
输出:
0 90
既然我们已经走到了这一步,我们不妨存储一个“长度”和重载__repr__
以使结果更漂亮:
class Prefix:
def __init__(self, length):
self.length = length
def __sub__(self, other):
result_length = self.length - other.length
return Prefix(result_length)
def __repr__(self):
result_m, result_cm = self.split_up(self.length)
if result_m > 0:
return f'{result_m}m {result_cm}cm'
else:
return f'{result_cm}cm'
@staticmethod
def split_up(length):
return divmod(length, 100)
Prefix(220) - Prefix(130)
输出:
90cm
推荐阅读
- typescript - 如何在打字稿中向声明的类添加方法
- android - 如何从这个 JSON 中一次获取评论列表并将其传递给 recyclerview 适配器
- listview - Flutter 中刷新 ListView
- scala - 执行多个 Spark 作业
- regex - 正则表达式获取两个单词之间的所有内容 {}
- asp.net - ASP.NET MVC 将数据从控制器传输到使用 viewmodel 的视图
- r - 不要使用前哨 1 数据工作 prepSentinel
- c++ - 列表初始化的重载解析规则是什么
- java - 带有 Intellij 的 Gradle 6 - 刷新失败
- sql - 查询从字符串中提取单词