Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply max & min boundaries to a value without using conditional statements

Tags:

python

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!

like image 866
user2066771 Avatar asked Feb 16 '13 19:02

user2066771


People also ask

How do you use Max?

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.

What is Max () function in Excel?

Returns the largest value in a set of values.

How do you use Max in condition?

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)).”


1 Answers

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:

  • lo, when x < lo: if lo < hi, then x < hi, so min(hi, x) returns x and max(lo, x) returns lo.
  • hi, when x > hi: min(hi, x) returns hi and if lo < hi, max(lo, hi) returns hi
  • x, otherwise: x > lo and x < hi, so min(hi, x) returns x and max(lo, x) returns x
like image 52
Nicolas Avatar answered Nov 14 '22 23:11

Nicolas