Problem:
Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x is greater than hi; and x otherwise. For this problem, you can assume that lo < hi.
Don't use any conditional statements for this problem. Instead, use the built in Python functions min and max. You may wish to read the documentation on min and the documentation on max, and play around with these functions a bit in your interpreter, before beginning this problem.
This function takes in three numbers and returns a single number.
Code Given:
def clip(lo, x, hi):
'''
Takes in three numbers and returns a value based on the value of x.
Returns:
- lo, when x < lo
- hi, when x > hi
- x, otherwise
'''
My Code Added:
def clip(lo, x, hi):
'''
Takes in three numbers and returns a value based on the value of x.
Returns:
- lo, when x < lo
- hi, when x > hi
- x, otherwise
'''
if min(x, lo, hi) == x:
return lo
elif max(x, lo, hi) == x:
return hi
else:
return x
Here's the problem: I can't use ANY conditionals. Help!
MAX will return the largest value in a given list of arguments. From a given set of numeric values, it will return the highest value. Unlike MAXA function, the MAX function will count numbers but ignore empty cells, text, the logical values TRUE and FALSE, and text values.
Returns the largest value in a set of values.
The IF function is a conditional function that displays results based on certain criteria. The MAX IF function identifies the maximum value from all the array values that match the logical test. The formula of Excel MAX If function is “=MAX(IF(logical test,value_ if _true,value_if_ false)).”
Here is a solution, assuming that lo < hi.
def clip(lo, x, hi):
return max(lo, min(hi, x))
How it works in each case:
min(hi, x)
returns x
and max(lo, x)
returns lo
.min(hi, x)
returns hi
and if lo < hi, max(lo, hi)
returns hi
min(hi, x)
returns x
and max(lo, x)
returns x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With