y=if x>High: 2 elif x<Low: 1 else: 0

Stephen Horne steve at lurking.demon.co.uk
Wed Jun 5 00:52:41 CEST 2002


On Wed, 22 May 2002 19:12:10 -0400, Steven Majewski
<sdm7g at Virginia.EDU> wrote:

>I prefer:
>
>>>> ( 2, 1, 0 )[ [ x > hi, x < low, 1  ].index(1)]
>
>as more readable, although the lambda functional version gets a bit
>more baroque:
>
>>>> (lambda x: (2,1,0)[(lambda x: [x > hi, x < low, 1])(x).index(1)])(arg)

Hmmm

I occasionally use the following little trick...


def IF(p_Condition, p_True, p_False=lambda: None) :
  """
  Expects parameterless functions or lambdas for the p_True
  and p_False arguments
  """
  if p_Condition : return p_True ()
  return p_False ()

#...

print IF(x != 0, lambda: 5 // x)


This could easily be adapted...

print IF(x>High, lambda:2, IF(x<Low, lambda:1, lambda:0))


and if multi-condition patterns are extensively used...

def FIRST (p_Tests, p_Default) :
  """
  p_Tests : a sequence of 2-tuples, each containing
            0 : A parameterless function for the test
            1 : A parameterless function for the value
  p_Default : A parameterless function for the default
              result if all tests fail.

  Example...

  FIRST( [(lambda: x<Low,  lambda: 1),
          (lambda: x>High, lambda: 2) ], lambda: 0 )

  """
  for l_Test,l_Value in p_Tests :
    if l_Test () :
      return l_Value ()
  return p_Default ()

  if p_Lo_Test () : return p_Lo_Result ()
  if p_Hi_Test () : return p_Hi_Result ()
  return p_Mid_Result ()


Actually, I prefer to use 'None' as the fail case in this pattern so
that the test and result can be bound in one function.

def FIRST (p_Functions) :
  """
  p_Functions : a sequence of parameterless functions,
                each either returning a valid result or
                None.

  Example...

  FIRST( [(lambda: x<Low  and 1 or None),
          (lambda: x>High and 2 or None),
          (lambda: 0                   ) ] )

  """
  for l_Function in p_Functions :
    l_Result = l_Function ()
    if l_Result != None : return l_Result
  return None


Personally, I think there should be an if 'function' built in which
has similar semantics to the IF function above but without needing the
lambdas. It would be nice if it also supported more than three
parameters - each pair giving an 'if' or 'elif' condition plus result
and the final odd parameter giving the 'else' result.

This would allow something like...

  if (x < Low : 1, x > High : 2, 0)




More information about the Python-list mailing list