如何使用模数运算符将一个数绑定在两个常数之间


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

我试图将x绑定在两个数字之间,20和100(不相容)。也就是说,一旦到达100,它应该循环回到20。

我知道它是如何工作的while循环,(while boundX <最小),但我有麻烦与>运算符和编写正确的表达式。

交货。boundThis(201)应该给我21,而boundThis(100)给我20

请注意,minmax已经是内置函数,因此不要使用这些标识符命名变量,因为您无法执行以下操作(假设您不试图在指定范围内生成数字列表):

>>> 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
编辑:

对于绕行条件,将其视为一个数学问题。正如你所知道的,模数运算符本质上是求除法运算后的余数,所以我们可以用它。所以如果你有0n的偏移量,基本情况就很简单了。

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

但是你希望它从一些基础值(low)偏移,所以你必须应用基本的数学并将该问题简化为上面的问题。我建议你在阅读下面的解决方案之前,试着自己弄清楚这个问题。

>>> 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

最新更新