Search code examples
pythonnumbers

Is there a simple way to do number operations in a limited number space in python?


I want to know if there is a simple method to do number equations in a limited number space like 0 and 40 or 0 and 1000? Even better if there is a way for numbers to go back.

For example, have a number space between 0 and 8. Then do operation 4 + 7 which would be equal to 11 (over 8) and then this number will go back to 5, because 4 + 4 would be 8 and because there is still a residue of 3 (7 - 4 = 3) which then equal to 8 - 3 which is 5. And vice versa with substraction where 3 - 4 would be equal to 1 in a 0 to 8 number space.

I tried to do bunch of ifs, but stopped, because it made code a little bit complicated.


Solution

  • It's periodic with period twice the size of your space. For example with space from 0 to 8, adding 16 or 32 or 48 etc doesn't have an effect. So use modulo twice the size. Then you have at most one bump off a wall, which I handled with a min. To support nonzero lower ends, surround the actual calculation by shifting the lower end to zero and back (i.e., subtract lo from the given a and add it back at the end).

    def add(a, b, lo, hi):
        p = 2 * (hi-lo)
        s = (a-lo + b) % p
        return min(s, p-s) + lo
    
    def sub(a, b, lo, hi):
        return add(a, -b, lo, hi)
    
    print(add(4, 7, 0, 8))
    print(sub(3, 4, 0, 8))
    print(*(add(5, i, 3, 6) for i in range(15)))
    

    Output (Attempt This Online!):

    5
    1
    5 6 5 4 3 4 5 6 5 4 3 4 5 6 5