Conditional operator in Python?
thp at cs.ucr.edu
thp at cs.ucr.edu
Tue Sep 4 03:58:56 EDT 2001
On Tue, Sep 04, 2001 at 09:48:13AM +0200, Mikael Olofsson wrote:
>
> On 04-Sep-2001 thp at cs.ucr.edu wrote:
> > 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.
>
> Well, both are just as hard to read to me, but then I have never used
> C. I (almost) always use if-then-else, since that fits my small brain
> best. Sure, it needs more rows, but I prefer that to both variations of
> line noise above.
So, replace "?" by "then" and ":" by "else", obtaining:
p = lambda k, n :
k < 1 or k > n then
0
else n == 1 or n == k then
1
else
p( k-1, n-1 ) + p (k, n-k )
which reads better with a couple of if's added:
p = lambda k, n :
if k < 1 or k > n then
0
else if n == 1 or n == k then
1
else
p( k-1, n-1 ) + p (k, n-k )
I'm not lobbying for ?: notation in particular. I simply want
something better than (a and [b] or [c])[0]. In fact, the
if/then/else notation is my personal favorite.
Regards,
Tom Payne
More information about the Python-list
mailing list