Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用模运算符在两个常量之间绑定数字? def boundThis(x): 最小值=20 最大值=100 boundX=int(x) 如果(boundX>最大值): boundX=boundX%max+min-1 如果(boundX>最大值): boundX-=max-1 其他: 而(边界x_Python_Algorithm - Fatal编程技术网

Python 如何使用模运算符在两个常量之间绑定数字? def boundThis(x): 最小值=20 最大值=100 boundX=int(x) 如果(boundX>最大值): boundX=boundX%max+min-1 如果(boundX>最大值): boundX-=max-1 其他: 而(边界x

Python 如何使用模运算符在两个常量之间绑定数字? def boundThis(x): 最小值=20 最大值=100 boundX=int(x) 如果(boundX>最大值): boundX=boundX%max+min-1 如果(boundX>最大值): boundX-=max-1 其他: 而(边界x,python,algorithm,Python,Algorithm,我试图将x限定在两个数字之间,20和100(不包括)。也就是说,一旦它达到100,它应该循环回到20 我知道它是如何与while循环一起工作的,(while boundX

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

我知道它是如何与while循环一起工作的,(while boundX
例:boundThis(201)应该给我21,boundThis(100)应该给我20。

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

编辑:

对于环绕条件,将其视为一个数学问题。正如你们所知道的,模运算符基本上是找到除数上除法运算剩下的剩余部分,所以我们可以使用它。因此,如果偏移量为
0
n
,则基本情况非常简单

>>> 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
但是你想让它偏离某个基本值(
),所以你必须应用基本数学,把这个问题简化为上面的问题。在阅读下面的解决方案之前,我建议您自己尝试解决这个问题

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

可能的复制品,尽管实际上仔细观察。。。。你是不是想把数字绕起来,而不是夹起来?也就是说,
min=10,max=15
number=9,output=15
number=16,output=10
?即使您试图生成一个列表,它也可以正常工作,您只需使用列表理解,如
list=[bind(20100,value)表示数值]
@WCGPR0我的任一解决方案(针对您以前的问题和已澄清的问题)没有涉及任何递归。。。
>>> 99 % 100
99
>>> 101 % 100
1
>>> 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