16

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

?

Double AA
  • 5,759
  • 16
  • 44
  • 56

8 Answers8

25
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
nmichaels
  • 49,466
  • 12
  • 107
  • 135
3

If you're doing modular arithmetic, you simply need to use the modulo operator.

x = (x + y) % 48
JAB
  • 20,783
  • 6
  • 71
  • 80
3

Wouldn't just (x+ y)% 48 be suitable for you. See more on modulo here.

eat
  • 7,440
  • 1
  • 19
  • 27
2

you can use the modulo operator:

x = (x+y) % 48
Andre Holzner
  • 18,333
  • 6
  • 54
  • 63
2

You can just use

x = (x+y) % 48

which will give you positive x for any numbers.

Howard
  • 38,639
  • 9
  • 64
  • 83
1

You could also make a class to handle modular arithmetic, like have been done here: http://anh.cs.luc.edu/331/code/mod_arith.py
http://anh.cs.luc.edu/331/code/mod.py

peterhil
  • 1,536
  • 1
  • 11
  • 18
1

(x + y) % 48

Replace 48 with whatever you please.

Doug Stephen
  • 7,181
  • 1
  • 38
  • 46
0

You may need the result of the division besides the remainder modulo n, so here's a seconds-to-year+days+etc translator which demonstrates the divmod function. Of course, one could go on to lustrum, decades, scores, century, or use fortnight or such. ;)

nsec = 1989550000
mnt2sec = 60; hrs2mnt=60; day2hrs=24; yrs2day=365
mnt, dus = divmod(nsec, mnt2sec)
hrs, dum = divmod(mnt, hrs2mnt)
dys, duh = divmod(hrs, day2hrs)
yrs, dud = divmod(dys, yrs2day)
print(f'{nsec} s = {yrs} y, {dud} d, {duh} h, {dum} m, {dus} s')
# check
asec = (dus+mnt2sec*(dum+hrs2mnt*(duh+day2hrs*(dud+yrs*yrs2day))))
assert asec == nsec, "wrong sum rule"
Jiho Choi
  • 1,083
  • 1
  • 10
  • 26