<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>mikhail panchenko / blog &#187; trick</title>
	<atom:link href="http://mihasya.com/blog/tag/trick/feed/" rel="self" type="application/rss+xml" />
	<link>http://mihasya.com/blog</link>
	<description>good things now come in packages of three</description>
	<lastBuildDate>Sat, 14 Jan 2012 07:28:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Ternary in Python: The Cover Beats the Original</title>
		<link>http://mihasya.com/blog/ternary-in-python-the-cover-beats-the-original/</link>
		<comments>http://mihasya.com/blog/ternary-in-python-the-cover-beats-the-original/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 08:51:19 +0000</pubDate>
		<dc:creator>mihasya</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[ternary]]></category>
		<category><![CDATA[trick]]></category>
		<category><![CDATA[tuple]]></category>

		<guid isPermaLink="false">http://mihasya.com/blog/?p=220</guid>
		<description><![CDATA[Like most newcomers to Python, I lamented the absence of a ternary operator. Some say the operator is hard to read, but I say those people need better reading glasses. If I want to assign a value based on a condition, I don&#8217;t think there&#8217;s anything clearer than an operator triad that exists solely for [...]]]></description>
			<content:encoded><![CDATA[<p>Like most newcomers to Python, I lamented the absence of a ternary operator. Some say the operator is hard to read, but I say those people need better reading glasses. If I want to assign a value based on a condition, I don&#8217;t think there&#8217;s anything clearer than an operator triad that exists solely for that purpose.</p>

<p>In any case, Python doesn&#8217;t have the standard = ? : ternary. It has a similar shorthand if-else construct, which I used begrudgingly. It looks like this:
<pre>result = value1 if condition else value2</pre>
THAT is hard to read. Code highlighting helps, but it&#8217;s still far from optimal.</p>

<h3>This Kung Fu Is Weak!</h3>

<p>Then I stumbled upon <a title="Simulating ternary operator in python" href="http://www.wellho.net/mouth/657_The-ternary-operator-in-Python.html">this random page</a> while looking up exactly what the syntax was. The trick is to build a <a title="Python Manual page for Tuples" href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences">tuple</a> on the fly and immediately select one of its elements using the condition as the index. The above code ends up looking like this:
<pre>result = (value1, value2)[condition]</pre>
How fucking awesomely elegant is that? As the post title suggests, I actually like this better than the original ternary.</p>

<p>As if to compliment this trick, the bool type in Python actually evaluates to a numeric 0 or 1. This makes the classic &#8220;Set the value to itself if it&#8217;s already set; set it to X otherwise&#8221; case incredibly easy:
<pre>value = (value, X)[bool(value)]</pre>
A frequent use case is one where you have a function argument that you want to default to a certain value calculated using another function. It can&#8217;t just be set in the function signature; you end up setting it to None in the signature (which, IMO, you should have done to begin with), then assigning it whatever the default value is if the caller doesn&#8217;t pass anything.</p>

<p>Here&#8217;s a real example: an implementation of <a title="Binary Search on Wikipedia" href="http://en.wikipedia.org/wiki/Binary_search">Binary Search</a> in Python. (I&#8217;ve been going through <em><a title="Intro to Algorithms on Amazon" href="http://www.amazon.com/Introduction-Algorithms-Thomas-Cormen/dp/0072970545/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1232786545&amp;sr=8-1">Introduction to Algorithms</a></em> as part of my New Years resolution to become a better programmer; I hate writing pseudo code, so I&#8217;ve been writing Python for all the exercises)</p>

<p>UDPATE</p>

<p>Found an even better alternative for this case:
<pre>value = value or X</pre>
Example updated:
<pre>def binSearch(needle, haystack, start=None, end=None):
    start = start or 0
    end = end or len(haystack)-1</p>

<p>    midpt = start+int(math.floor((end-start)/2))
    median = haystack[midpt]
    if (needle &gt; median):
        return binSearch(needle, haystack, midpt, end)
    elif (needle &lt; median):
        return binSearch(needle, haystack, start, midpt)
    else:
        return midpt</pre>
Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://mihasya.com/blog/ternary-in-python-the-cover-beats-the-original/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

