Conditional operator in Python?

Donn Cave donn at u.washington.edu
Tue Sep 4 13:04:59 EDT 2001


Quoth thp at cs.ucr.edu:
...
| 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.

I am working intermittently on a modification to some code that was
written in C by someone with a compulsion for syntax like that.
I spent many hours on a trivial rewrite of a module of his like
the one I want to write, just so I could read it.

Though the second example may be more concise and readable than
the first, it's much less readable than a normal procedural solution.
The first on the other hand has the advantage that only the most
obtuse author could argue that it's readable at all, while the
second sort of legitimizes this kind of obfuscation in Python.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list