Modular addition in python
Asked Answered
P

8

18

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

?

Planetstruck answered 13/7, 2011 at 20:14 Comment(0)
D
26
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
Dvinsk answered 13/7, 2011 at 20:16 Comment(0)
B
3

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

x = (x + y) % 48
Brocket answered 13/7, 2011 at 20:17 Comment(0)
I
3

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

Ivatts answered 13/7, 2011 at 20:18 Comment(0)
S
2

you can use the modulo operator:

x = (x+y) % 48
Side answered 13/7, 2011 at 20:17 Comment(0)
R
2

You can just use

x = (x+y) % 48

which will give you positive x for any numbers.

Rhapsody answered 13/7, 2011 at 20:17 Comment(1)
Nonnegative x (could be 0).Genevagenevan
D
1

(x + y) % 48

Replace 48 with whatever you please.

Dragging answered 13/7, 2011 at 20:19 Comment(0)
T
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

Tritheism answered 11/8, 2014 at 10:25 Comment(0)
D
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"
Discuss answered 7/5, 2023 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.