程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python code reading (Chapter 49): limit a number to a specified range

編輯:Python
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_number

def 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)) # -1

clamp_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 ab The comparison between the minimum value and the maximum value .

  1. max(a, b) This step calculates the upper limit of the specified range α.
  2. 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.
  3. min(a, b) This step calculates the lower limit of the specified return β.
  4. In the last step, there are two situations , Namely max(α, β) and max(num, β).

    • When 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 .
    • When 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 .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved