Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bound a number between two constants using the modulus operator?

def boundThis(x):
    min = 20
    max= 100
    boundX = int(x)
    if (boundX > max):
        boundX = boundX % max + min-1
        if (boundX > max):
          boundX-=max-1
    else:
        while(boundX < min):
            boundX += max-min
    return boundX

I'm trying to bound x between two numbers, 20 and 100 (exclusive). That said, once it hits 100, it should loop back to 20.

I get how it works with the while loop, (while boundX < min) but am having trouble with the modulus operator and writing the correct expression with that.

Ex. boundThis(201) should give me like 21, and boundThis(100) giving me 20.

like image 420
WCGPR0 Avatar asked Dec 25 '22 12:12

WCGPR0


1 Answers

Do note that min and max are already builtin functions, so don't name variables with those identifiers as you can't do something like the following (assuming you are not trying to generate a list of numbers within the specified bounds):

>>> def bound(low, high, value):
...     return max(low, min(high, value))
... 
>>> bound(20, 100, 1000)
100
>>> bound(20, 100, 10)
20
>>> bound(20, 100, 60)
60

Edit:

For the wrap around condition, think of this as a math problem. As you know the modulus operator essentially finds the remainder of what is left over from a division operation on a divisor, so we can use that. So the base case is very simple if you have an offset of 0 to n.

>>> 99 % 100
99
>>> 101 % 100
1

But you want it offset from some base value (low), so you have to apply basic mathematics and reduce that problem to the one above. I would suggest you try to figure this out on your own before reading the solution below.

>>> def bound(value, low=20, high=100):
...     diff = high - low
...     return (((value - low) % diff) + low)
...
>>> bound(0)
80
>>> bound(19)
99
>>> bound(20)
20
>>> bound(100)
20
>>> bound(99)
99
like image 160
metatoaster Avatar answered Apr 29 '23 07:04

metatoaster