Python Code reading collection Introduction : Why not recommend Python Beginners directly look at the project source code
The code read in this article realizes the function of limiting a number to a specified range , If this number is within the range specified by the other two numbers , Will maintain its own value , Otherwise, it returns the value closest to this number .
The code snippet read in this article comes from 30-seconds-of-python.
clamp_numberdef clamp_number(num,a,b):
return max(min(num, max(a, b)), min(a, b))
# EXAMPLES
print(clamp_number(2, 3, 5)) # 3
print(clamp_number(1, -1, -5)) # -1clamp_number The number of functions that need to be received is limited num, And two numbers that represent the return a and b, Returns the result of the restriction .
Different from multiple use if Conditional statements , This function is used in combination with max and min Function to find the result of the limit .
The logic of the code is to get a and b The maximum of , And again num Find the minimum value . This minimum is then combined with a、b The comparison between the minimum value and the maximum value .
max(a, b) This step calculates the upper limit of the specified range α.min(num, α) This step is to find the minimum value in the upper limit of the specified value and range . Only when the specified value exceeds the upper limit of the range , The return value is α, Other situations return to num.min(a, b) This step calculates the lower limit of the specified return β. In the last step, there are two situations , Namely max(α, β) and max(num, β).
num When the upper limit of the range is exceeded , The last step is max(α, β). At this time, the upper limit of the range is returned α, Is the closest in the whole value range num Value .num When the upper limit of the range is not exceeded , The last step is max(num, β). If at this time num Within the range of values , It will be greater than the lower limit of the range β, return num. If num Less than the lower limit of the range β, Then return to β, Is the closest in the whole value range num Value .