Im trying to subtract with prefixes as objects.

Here is my code

class Prefix:   
    def __init__(self, m=0, cm=0):

       self.m = m = cm

    def __sub__(self, other):

       centim = -
       meter = (self.m - other.m) - abs(centim/100)

       if meter < 1:
          centim = m*100
          meter = 0
          return Prefix(meter, cm)

Im trying to subtract in a way which creates a negative centimeter value and take 1m from the meter object such that this is fulfilled

Prefix(2, 20) - Prefix(1, 30) == Prefix(0, 90)

1 Answers

Marcus Lim On

First, keep in mind that for a given length, everything to the right of the hundreds place goes into cm, and everything at it or to its left gets divided by 100, and then goes into m.

Given this, we can recast the problem as converting both Prefix objects into their full lengths, performing calculations there, and then creating a new Prefix from the result:

class Prefix:   

    def __init__(self, m=0, cm=0):
        self.m = m = cm

    def __sub__(self, other):
        self_length = self.m * 100 +
        other_length = other.m * 100 +

        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)


0 90

Since we've come this far, we might as well store a "length" and overload __repr__ to make the result prettier:

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'
            return f'{result_cm}cm'

    def split_up(length):
        return divmod(length, 100)

Prefix(220) - Prefix(130)