Modular addition in python

Double AA picture Double AA · Jul 13, 2011 · Viewed 41.2k times · Source

I want to add a number y to x, but have x wrap around to remain between zero and 48. Note y could be negative but will never have a magnitude greater than 48. Is there a better way of doing this than:

x = x + y
if x >= 48:
    x = x - 48
elif x < 0:
    x = x + 48

?

Answer

nmichaels picture nmichaels · Jul 13, 2011
x = (x + y) % 48

The modulo operator is your friend.

>>> 48 % 48
0: 0
>>> 49 % 48
1: 1
>>> -1 % 48
2: 47
>>> -12 % 48
3: 36
>>> 0 % 48
4: 0
>>> 12 % 48
5: 12