简体   繁体   中英

check if number is in given range?

Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))

You can try

 def is_in_range(n, r):
     return r['min'] <= n <= r['max']

 print(is_in_range(4, { "min": 0, "max": 5 }))
 print(is_in_range(1, { "min": 4, "max": 5 }))

Output

True
False

You can try something like this

r = {'min':4, 'max':5}
n = 1

def isin(r,n):
    return (n>=r['min']) & (n<=r['max'])

Rather than looping, you can directly check whether:

if n>=r['min'] and n<=r['max']:
    return True
else:
    return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM