pythonpython-3.x

Python: keep the number in a specific range


I have a problem that runs like this:

I have an integer n, let n = 30, and a given range of numbers x and y that x < y, say 20 and 35.
I add n with another integer k. Say, k = 19.

However, I want to keep n between x and y. So if n+k > 35 it jumps back to 20 at 36, then continue to add 13 (19-6=13), which the final answer is 33.

I have already done the problem from scratch, and it's lengthy. It looks like this:

def plus(n,k,x,y):
   result = n+k
   if result > y: #do sth
   if result < x: #do sth
   return result

My question is, is there any build-in method, in any library, that helps me to do this problem? Thanks a lot.


Solution

  • The modulo operator % performs the kind of wrapping you're looking for. a % b gives the remainder from dividing a by b, resulting in the following wraparound pattern:

    >>> for i in range(-2, 12):
    ...     print(f"{i} % 5 = {i % 5}")
    ... 
    -2 % 5 = 3
    -1 % 5 = 4
    0 % 5 = 0
    1 % 5 = 1
    2 % 5 = 2
    3 % 5 = 3
    4 % 5 = 4
    5 % 5 = 0
    6 % 5 = 1
    7 % 5 = 2
    8 % 5 = 3
    9 % 5 = 4
    10 % 5 = 0
    11 % 5 = 1
    

    (The results you see with a negative left operand aren't what you get in most languages. Most languages would give you -2 and -1 instead of 3 and 4, but the 3 and 4 answers turn out to be more useful.)

    You want to stay in a range from x to y inclusive instead of 0 to y-1, so we need to add and subtract x to adjust the range % gives us:

    def plus(n,k,x,y):
        modulus = y-x+1
        return (n+k-x) % modulus + x
    

    Sample output:

    >>> plus(30, 19, 20, 35)
    33
    >>> plus(30, 0, 20, 35)
    30
    >>> plus(30, 5, 20, 35)
    35
    >>> plus(30, 6, 20, 35)
    20
    >>> plus(30, -10, 20, 35)
    20
    >>> plus(30, -11, 20, 35)
    35