首页 > 解决方案 > 以公制前缀作为对象的减法

问题描述

我试图用前缀作为对象减去。

这是我的代码

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)

标签: pythonpython-3.x

解决方案


首先,请记住,对于给定的长度,百位右侧的所有内容都进入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

推荐阅读