Conditional operator in Python?
thp at cs.ucr.edu
thp at cs.ucr.edu
Tue Sep 4 17:15:21 EDT 2001
Donn Cave <donn at u.washington.edu> wrote:
: 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.
So:
- Put "if" before each condition.
- Replace ":" by "else".
- Replace "?" by ": return".
: Though the second example may be more concise and readable than
: the first, it's much less readable than a normal procedural solution.
I don't see why, say
if by_land():
lantern_count = 1
elif by_sea():
lantern_count = 2
else:
lantern_count = 0
should be more readable than, say
lantern_count =
if by_land() : 1
elif by_sea() : 2
else : 0
or simply
lantern_count = if by_land(): 1 elif by_sea(): 2 else: 0
: 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.
Lambda abstraction is a powerful feature that needs to be supported
with a selection operator. The ?: notation is not the only option
for such a ternary operator.
Tom Payne
More information about the Python-list
mailing list