Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 03:24:13 EDT 2001


Mikael Olofsson <mikael at isy.liu.se> wrote:

: On 04-Sep-2001 thp at cs.ucr.edu wrote:
:  >  Terry Reedy <tjreedy at home.com> wrote:
:  >  
:  > : <thp at cs.ucr.edu> wrote in message news:9n1hr7$7op$1 at glue.ucr.edu...
:  > :> I hate writing:
:  > :>
:  > :>   factorial = lambda x : (x<=1 and [1] or [x*factorial(x-1)])[0]
:  >  
:  > : Since 1 != 0, quite dependably, you do not need to. try "x<=1 and 1 or
:  > : x*factorial(x-1)"

: Interesting. If I were to write a factorial using a lambda, I would probably
: have written

:   factorial = lambda x: reduce(lambda a,b:a*b,range(1,x+1))

: or 

:   import operator
:   factorial = lambda x: reduce(operator.__mul__, range(1,x+1))

: Those two throw exceptions for non-positive input, which I prefer. But
: regrettably, they give rather stupid error messages. 

Okay, factorial is a somewhat simplistic example.  Consider the
following function, which counts the k-way partitions of n:

  p = lambda k, n : (
      ( k < 1  or k > n  ) and [0] or 
      ( n == 1 or n == k ) and [1] or 
      [p(k-1,n-1)+p(k,n-k)] 
    )[0]

Using, say, ?: notation this would be written:

  p = lambda k, n : 
    k < 1  or k > n  ? 0 :
    n == 1 or n == k ? 1 :
    p( k-1, n-1 ) + p (k, n-k )

which seems much more concise and readable.

Tom Payne




More information about the Python-list mailing list