Thursday, September 30, 2010

Simulating a Conditional Expression via a List Indexed by a Boolean

It is often the case that you need to shave off just a few characters off a piece of code (there are many competitions where code length is restricted, such as the JS1K competition). The following describes a good way to condense conditional expressions. NOTE: This method only works if your condition returns True or False, or 1 and 0. It will not work if your condition returns, say, a non-zero value for True.

This is what it looks like:
first if condition else second
is equivalent to
[second, first][condition]
This works because condition will return True or False; True in Python is equivalent to 1 and False is equivalent to 0. We then use this 1 or 0 as the index to a list containing first and second; if the condition returns 0, we get the 0th item of the list: second. If it returns 1, we get the 1st item: first.

Pretty neat, huh?

EDIT 05/08/11: True conditional expressions only evaluate the output term. To get this effect, wrap each term in a lambda and call the entire expression's result.
[lambda: second, lambda: first][condition]()

No comments:

Post a Comment