How to limit a number to be within a specified range? (Python)
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
or functionally equivalent:
clamp = lambda n, minn, maxn: max(min(maxn, n), minn)
now, you use:
n = clamp(n, 7, 42)
or make it perfectly clear:
n = minn if n < minn else maxn if n > maxn else n
even clearer:
def clamp(n, minn, maxn):
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n
Limiting a number to a range
If you want to be fancy about it, this works nicely:
r, g, b = (min(255, max(0, c)) for c in (r, g, b))
Example:
In [1]: r, g, b = -1, 145, 289
In [2]: r, g, b = (min(255, max(0, c)) for c in (r, g, b))
In [3]: r, g, b
Out[3]: (0, 145, 255)
Python make a number loop within a range
Just figured it out.
def loop(n, minn, maxn):
while n > maxn:
n = n - (maxn - minn)
while n < minn:
n = n + (maxn - minn)
return n
I think that should work for most cases, including negative numbers and ranges.
Limiting user input to a range in Python
Use a while
loop to keep asking them for input until you receive something you consider valid:
shift = 0
while 1 > shift or 26 < shift:
try:
# Swap raw_input for input in Python 3.x
shift = int(raw_input("Please enter your shift (1 - 26) : "))
except ValueError:
# Remember, print is a function in 3.x
print "That wasn't an integer :("
You'll also want to have a try-except
block around the int()
call, in case you get a ValueError
(if they type a
for example).
Note if you use Python 2.x, you'll want to use raw_input()
instead of input()
. The latter will attempt to interpret the input as Python code - that can potentially be very bad.
How to clamp an integer to some range?
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.
new_index = max(0, min(new_index, len(mylist)-1))
Related Topics
How to Perform Union on Two Dataframes With Different Amounts of Columns in Spark
Pandas: Subtracting Two Date Columns and the Result Being an Integer
How to Get Maximum Length of Each Column in the Data Frame Using Pandas Python
Return Value from Python-Shell as Response
How to Get the Sum of a CSV Column List to Print
How to Remove Name and Dtype from Pandas Output
Getting Value in a Dataframe in Pyspark
Split/Explode a Column of Dictionaries into Separate Columns With Pandas
How to Remove Zeros After Decimal from String Remove All Zero After Dot
How to Check If Keras Is Using Gpu Version of Tensorflow
Checking If a Button Has Been Pressed in Python
How to Map the Differences Between Two Strings
Delete Rows Containing Numeric Values in Strings from Pandas Dataframe
How to Find a Minimum Value in a 2D Array Without Using Numpy or Flattened in Python
Making a Matrix in Python 3 Without Numpy Using Inputs
How to Fill Empty Cell Value in Pandas With Condition
How to Find the Average Colour of an Image in Python With Opencv