Created
May 18, 2024 09:01
-
-
Save w-e-w/cac0787539a8163b94315c8d587ba952 to your computer and use it in GitHub Desktop.
Generate a function that checks if a list of value is in the interval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def parse_interval_rule(symbols, num): | |
match symbols: | |
case '[': | |
return lambda n: n >= num | |
case '(': | |
return lambda n: n > num | |
case ']': | |
return lambda n: n <= num | |
case ')': | |
return lambda n: n < num | |
def interval(interval_str): | |
""" | |
Generate a function that checks if a list of value is in the interval | |
Input interval_str in math notation ie '[min' 'max]', '(min', 'max]' '[min, max]' '(min, max)' '(min, max]' '[min, max)' | |
Return a function that checks if all value is in the interval else raise an error | |
""" | |
rules = [] | |
for items in re.finditer(r'([\[\]()])?\s*([\d.]+)\s*([\[\]()])?', interval_str): | |
num = float(items.group(2)) | |
if s := items.group(1): | |
rules.append(parse_interval_rule(s, num)) | |
if e := items.group(3): | |
rules.append(parse_interval_rule(e, num)) | |
def check_interval(xs): | |
for rule in rules: | |
for x in xs: | |
if not rule(x): | |
raise ValueError(f'value {x} must be in the interval {interval_str}') | |
return check_interval | |
if __name__ == '__main__': | |
test = interval('(100,200)') | |
test([150]) # pass | |
test([100]) # fail | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment