Write a small function and make it pass its checks.
What to build
A function clamp(x, low, high).
Requirements
clampreturnsxif it is betweenlowandhigh.- If
xis belowlow, it returnslow. Ifxis abovehigh, it returnshigh. - Each input line is one case, and the starter prints the result.
Input
The first line has n. Each of the next n lines has x, low and high.
Output
One number per line.
Constraints
n is from 1 to 50, and low is at most high.
Example
Input:
2
5 0 10
-3 0 10
Output:
5
0
Why it works
Edge cases such as x equal to low, or low equal to high, are exactly where a slip in the comparisons would show.
Examples
Example 1 · Input
2 5 0 10 -3 0 10
Expected output
5 0
Example 2 · Input
1 15 0 10
Expected output
10
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
If x is below low, return low. If it is above high, return high.
Hint 2
Think about values exactly equal to low or high.
Solution
Show one correct solution (try it yourself first)
def clamp(x, low, high):
if x < low:
return low
if x > high:
return high
return x
n = int(input())
for _ in range(n):
x, low, high = [int(v) for v in input().split()]
print(clamp(x, low, high))