3

I have a program that takes two imperial lengths (miles, yards, feet and inches) and outputs their sum and difference. My problem is that when the difference is negative, the output is incorrect.

def to_inches(miles, yards, feet, inches):
    return inches + (feet * 12) + (yards * 36) + (miles * 63360)


def from_inches(inches):
    miles = inches // 63360
    inches %= 63360

    yards = inches // 36
    inches %= 36

    feet = inches // 12
    inches %= 12

    return (miles, yards, feet, inches)

units1 = [int(n) for n in input().split(' ')]
units2 = [int(n) for n in input().split(' ')]

m_sum = from_inches(to_inches(*units1) + to_inches(*units2))
m_diff = from_inches(to_inches(*units1) - to_inches(*units2))

print(' '.join(str(n) for n in m_sum))
print(' '.join(str(n) for n in m_diff))

Input:

2 850 1 7
1 930 1 4

Output:

4 21 0 11
0 1680 1 3

Input:

0 1 0 0
1 0 0 0

Expected output:

1 1 0 0
-0 1759 0 0

Actual output:

1 1 0 0
-1 1 0 0
alexia
  • 14,440
  • 8
  • 42
  • 52

1 Answers1

2

It's because Python handles the mod operator % a bit weird when it comes to negative numbers. Check out this answer: https://stackoverflow.com/a/3883019/436282

Community
  • 1
  • 1
Andrew
  • 4,953
  • 15
  • 40
  • 58
  • Apparently, the same is true for the integer division operator (`//`). So I ended up using `int(math.fmod(x, y))` and `int(x / y)`. Also, I added a check to make only the first number negative if any of them are negative. – alexia Jul 17 '14 at 08:52