Drill

ProblemsPython › validation

Keep a value inside its range

easyvalidationPython

A slider hands back whatever the user dragged it to, and the settings layer pins it into the range the setting allows.

clamp_to_range(amount: int, low: int, high: int) → int

Solve it in the editor →

Where you start

def clamp_to_range(amount: int, low: int, high: int) -> int:
    

Worked examples

CallResult
clamp_to_range(5, 1, 10)5
clamp_to_range(0, 1, 10)1
clamp_to_range(99, 1, 10)10
clamp_to_range(5, 10, 1)5

Hint

Sort the bounds first and the rest is two comparisons.

Reference solution in Python
def clamp_to_range(amount: int, low: int, high: int) -> int:
    lo, hi = min(low, high), max(low, high)
    return min(hi, max(lo, amount))

The same problem in another language

More validation problems in Python