Modular addition in python
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. I开发者_运维技巧s there a better way of doing this than:
x = x + y
if x >= 48:
x = x - 48
elif x < 0:
x = x + 48
?
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
If you're doing modular arithmetic, you simply need to use the modulo operator.
x = (x + y) % 48
Wouldn't just (x+ y)% 48
be suitable for you. See more on modulo here.
you can use the modulo operator:
x = (x+y) % 48
You can just use
x = (x+y) % 48
which will give you positive x
for any numbers.
(x + y) % 48
Replace 48 with whatever you please.
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
精彩评论