16.2k views
2 votes
GetInRange (x, a, b) Write the function getInRange (x, a, b) that takes 3 float values and forces x to lie between a and b. a is not necessarily less than b. If x is between the two bounds, it is returned unmodified. Otherwise, if x is less than the lower bound, return the lower bound, or if x is greater than the upper bound, return the upper bound. Use pythons as a programming language.

User Umakanth
by
6.5k points

1 Answer

7 votes

Answer:

def GetInRange(x, a, b):

if (a > b): a, b = b, a

if (x < a): return a;

if (x > b): return b;

return x;

Step-by-step explanation:

By swapping a and b if a>b you can proceed under the assumption that you only have to check if x<a or x>b, which simplifies the logic a lot.

User Iunfixit
by
6.1k points