<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Tom Switzer&#039;s Blog</title>
	<atom:link href="http://tixxit.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://tixxit.wordpress.com</link>
	<description>Programming, web development and algorithms</description>
	<lastBuildDate>Mon, 22 Mar 2010 17:14:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='tixxit.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Tom Switzer&#039;s Blog</title>
		<link>http://tixxit.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://tixxit.wordpress.com/osd.xml" title="Tom Switzer&#039;s Blog" />
	<atom:link rel='hub' href='http://tixxit.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Easy Multilingual Theming with XDV</title>
		<link>http://tixxit.wordpress.com/2010/03/22/easy-multilingual-theming-with-xdv/</link>
		<comments>http://tixxit.wordpress.com/2010/03/22/easy-multilingual-theming-with-xdv/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 17:08:08 +0000</pubDate>
		<dc:creator>Tom Switzer</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tixxit.wordpress.com/?p=105</guid>
		<description><![CDATA[I use Plone at work (and love it). Lately I&#8217;ve started getting into using XDV to theme my sites (3 so far). It&#8217;s fantastic. Our latest site was put up in a week (from start to finish) using Plone, collective.xdv and some team work. Anyways, we only had the English version up initially, while we [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=105&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I use <a title="Plone's Official Site" href="http://plone.org/">Plone</a> at work (and love it). Lately I&#8217;ve started getting into <a href="http://pypi.python.org/pypi/collective.xdv">using XDV to theme my sites</a> (3 so far). It&#8217;s fantastic. Our latest site was put up in a week (from start to finish) using Plone, collective.xdv and some team work. Anyways, we only had the English version up initially, while we waited on the translations. When they finally came through, I first plugged it all into Plone (using LinguaPlone), but now I had to update the theme to support the French site. Support for the :lang() CSS pseudo selector is lacking in some browsers, so I contemplated for a few minutes, then added 2 rules to my rules.xml file:</p>
<p><pre class="brush: xml;">
&lt;drop theme=&quot;//*[@lang='fr']&quot; if-content=&quot;/html[@lang!='fr']&quot; /&gt;
&lt;drop theme=&quot;//*[@lang='en']&quot; if-content=&quot;/html[@lang!='en']&quot; /&gt;
</pre></p>
<p>Problem solved! To handle language-specific CSS, I just created 2 new css files, one for English and one for French and added a lang attribute in the link element.</p>
<p><pre class="brush: xml;">
&lt;link lang=&quot;en&quot; href=&quot;style-en.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;link lang=&quot;fr&quot; href=&quot;style-fr.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
</pre></p>
<p>I did the same thing for static text and images as well.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tixxit.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tixxit.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tixxit.wordpress.com/105/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=105&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tixxit.wordpress.com/2010/03/22/easy-multilingual-theming-with-xdv/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b2ecd194174398696f1d9a80bf6a14fa?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tixxit</media:title>
		</media:content>
	</item>
		<item>
		<title>2D Convex Hulls: Graham Scan</title>
		<link>http://tixxit.wordpress.com/2010/03/01/graham-scan/</link>
		<comments>http://tixxit.wordpress.com/2010/03/01/graham-scan/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 21:04:58 +0000</pubDate>
		<dc:creator>Tom Switzer</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[computational geometry]]></category>
		<category><![CDATA[convex hull]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://tixxit.wordpress.com/?p=82</guid>
		<description><![CDATA[This is the 2nd post in a series of 3 on 2D convex hull algorithms. The first covered the Jarvis March and here I&#8217;ll be covering the Graham Scan. The implementation of the Graham Scan is short, but sweet. It handles degenerate cases very well. The next post will cover Chan&#8217;s algorithm. Graham Scan Although [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=82&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is the 2nd post in a series of 3 on 2D convex hull algorithms. The first covered the <a href="http://tixxit.wordpress.com/2009/12/10/graham-scan/">Jarvis March</a> and here I&#8217;ll be covering the <a href="http://en.wikipedia.org/wiki/Graham_Scan">Graham Scan</a>. The <a title="Graham Scan in Python" href="http://gist.github.com/242402">implementation of the Graham Scan</a> is short, but sweet. It handles degenerate cases very well. The next post will cover <a href="http://gist.github.com/252229">Chan&#8217;s algorithm</a>.</p>
<h3>Graham Scan</h3>
<p>Although it may not look it at first glance, the Graham Scan is similar to the Jarvis March. We start with an extreme point and then find the edges of the hull iteratively, one at a time. The main difference is that by sorting the points first, we remove the need to spend <em>O(n)</em> time searching for the next hull point, though at the cost of making some &#8220;mistakes&#8221; (adding points to the hull that aren&#8217;t hull points). Instead, we spend our effort on updating the hull at each iteration, fixing previous mistakes. It turns out that fixing the mistakes is pretty easy and we can find the entire hull in only <em>O(n)</em> comparisons (rather then the <em>O(nh)</em> of the Jarvis March). The time complexity of the algorithm actually comes from having to first sort the points in <em>O(n log n)</em> time. Now, much as we did with the Jarvis March, we will require a function that tells us the &#8220;turn&#8221; of 3 points (that is, whether p,q,r form a LEFT, RIGHT or straight (NONE) turn):</p>
<p><pre class="brush: python;">
TURN_LEFT, TURN_RIGHT, TURN_NONE = (1, -1, 0)

def turn(p, q, r):
    return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0)
</pre></p>
<p>The original incantation of the Graham Scan sorted the points in angular order relative to some initial extreme point (eg. sorted in CCW order around the furthest left point). The convex hull is then constructed iteratively by going through the sorted list of points, one by one, each time adding the point to the previous hull. However, adding a point to the previous hull in the Graham Scan is not as simple as it was in the Jarvis March. In the Jarvis March, we knew our previous hull points were a subset of our final hull points, so to &#8220;update&#8221; the previous hull, we simply add the point found at each iteration to the end of our list of hull points. However, in the Graham Scan, updating our list of hull points at each iteration is not as simple.</p>
<p>The hull we have at the start of iteration <em>i</em> is actually the complete convex hull of the first <em>i-1</em> points in our sorted list. Updating the hull requires us to find the tangents between the previous hull and point <em>p<sub>i</sub></em>, and replacing all hull edges between these 2 tangents with the tangents themselves. This may seem hard at first, but because the points were sorted in CCW order around the first point, <em>p<sub>1</sub></em>, it is actually quite simple.</p>
<p>We know the point <em>p<sub>i</sub></em> lies to the left of <em>p<sub>1</sub>p<sub>i-1</sub></em> and all other points <em>p<sub>k</sub>, 1 &lt; k &lt; i-1</em>, lie to the right of <em>p<sub>1</sub>p<sub>i-1</sub></em>, so one of the tangents will have to be the edge <em>p<sub>i</sub>p<sub>1</sub></em>. Knowing this, we can find the other point of tangency by starting at <em>p<sub>i-1</sub></em> (the last point in the list of hull points) and working backwards. The point of tangency is the first point <em>p<sub>j</sub>, j&lt;i</em>, where <em>p<sub>j-1</sub>, p<sub>j</sub>, p<sub>i</sub></em> form a left (CCW) turn. After finding the point <em>p<sub>j</sub></em>, we simply remove all points between this and the other point of tangency, <em>p<sub>1</sub></em> (ie. we simply remove all points after <em>p<sub>j</sub></em> in our hull list). The point <em>p<sub>i</sub></em> is then simply appended to the end of our list of hull points.</p>
<p>In Python, we can implement a function to perform this step (adding a point <em>r</em> to the <em>hull</em>) fairly simply: we just keep popping the last item off our list while hull[-2], hull[-1], r don&#8217;t form a left turn.</p>
<p><pre class="brush: python;">
def _keep_left(hull, r):
    while len(hull) &gt; 1 and turn(hull[-2], hull[-1], r) != TURN_LEFT:
        hull.pop()
    # We check that hull[-1] != r to handle degenerate cases (ie. multisets)
    if not hull or hull[-1] != r:
        hull.append(r)
    return hull
</pre></p>
<p>What&#8217;s nice is that we only backtrack through the list, starting at the last point, by as many points as we will remove, +1 more point pj (which is where we stop). After we remove these points, they will never be looked at again, since they are no longer in the hull. This means, if we account for the +1 point we don&#8217;t remove, we will never look at more than <em>2n</em> hull points during the entire run of the Graham Scan to find the tangents. Since we only go through the sorted list once, we require only O(n) time to find the convex hull, but O(n log n) time to sort the list first.</p>
<p>Putting it together, in Python, we could simply sort the list by angular order, using the turn function as the cmp function, then iterate through the sorted list of points add the points one at a time (with _keep_left). However, a nice (implementation) thing about the Graham Scan is that we can get away with sorting by lexicographical order, instead of angular order. Pretend we added a point at (0, ∞) to the point set. Then sorting by angular order about this point is equivalent to simply sorting by the x-coordinate. The convex hull of this modified point set is actually just the lower hull of our original point set. We can use this idea to split the algorithm into 3 parts. First we sort by x-coordinates (actually, lexicographical order to handle degenerecies) and find the lower hull. Then we reverse this sorted list and find the upper hull. Finally, we merge the upper and lower hull together. Doing this in Python, using the _keep_left function, is actually really straightforward. We simply have to keep in mind that the first point of the lower hull is also the last point of the upper hull and vice versa</p>
<p><pre class="brush: python;">
def convex_hull(points):
    &quot;&quot;&quot;Returns points on convex hull of an array of points in CCW order.&quot;&quot;&quot;
    points = sorted(points)
    l = reduce(_keep_left, points, [])
    u = reduce(_keep_left, reversed(points), [])
    return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l
</pre></p>
<p>I posted the <a title="Graham Scan in Python" href="http://gist.github.com/242402">full source for the Graham Scan in Python (all 20 lines) as a Gist</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tixxit.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tixxit.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tixxit.wordpress.com/82/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=82&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tixxit.wordpress.com/2010/03/01/graham-scan/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b2ecd194174398696f1d9a80bf6a14fa?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tixxit</media:title>
		</media:content>
	</item>
		<item>
		<title>2D Convex Hulls: Jarvis March</title>
		<link>http://tixxit.wordpress.com/2009/12/09/jarvis-march/</link>
		<comments>http://tixxit.wordpress.com/2009/12/09/jarvis-march/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 02:30:06 +0000</pubDate>
		<dc:creator>Tom Switzer</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[computational geometry]]></category>
		<category><![CDATA[convex hull]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://tixxit.wordpress.com/?p=52</guid>
		<description><![CDATA[I&#8217;ve found myself coding convex hull algorithms on a few occasions now, so I decided to implement a few and talk about them here, in case someone new to the subject wants to get the quick &#8216;n&#8217; dirty. The algorithms I will talk about are the Jarvis March (code), the Graham Scan (code) and Chan&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=52&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve found myself coding <a title="Convex hull on wikipedia" href="http://en.wikipedia.org/wiki/Convex_hull">convex hull</a> algorithms on a few occasions now, so I decided to implement a few and talk about them here, in case someone new to the subject wants to get the quick &#8216;n&#8217; dirty. The algorithms I will talk about are the <a title="Jarvis March (&quot;Gift Wrapping&quot;) on Wikipedia" href="http://en.wikipedia.org/wiki/Jarvis_march">Jarvis March</a> (<a href="http://gist.github.com/252222">code</a>), the <a title="Graham Scan on Wikipedia" href="http://en.wikipedia.org/wiki/Graham_scan">Graham Scan</a> (<a href="http://gist.github.com/242402">code</a>) and <a href="http://www.cs.uwaterloo.ca/~tmchan/conv23d.ps.gz">Chan&#8217;s algorithm</a> (<a href="http://gist.github.com/252229">code</a>). I feel they are all different enough that each is worth looking at, but similar enough that they are worth looking at together. I will try and focus more on the actual implementation of the algorithms (all in Python), looking at potential pit falls as well as the niceties, rather then just rehashing what can be found on Wikipedia. This first post looks at the Jarvis March.</p>
<h3>Jarvis March</h3>
<p>The Jarvis March is probably the simplest convex hull algorithm conceptually. You start with an <a href="http://en.wikipedia.org/wiki/Extreme_point">extreme point</a> <em>p</em> (a vertex of the convex hull) of a point set. You then find the next point on the convex hull of the point set in CCW order. This is done by finding the &#8220;furthest right&#8221; point, relative to <em>p</em>. The furthest right point <em>q</em>, relative to <em>p,</em> is the point such all other points in the point set lie to the left of the directed line through <em>p, q</em> (this line lies on the hull boundary). We can then update <em>p</em> to <em>q</em> and repeat the process until we end up with the point we started at.</p>
<div id="attachment_78" class="wp-caption alignright" style="width: 160px"><a href="http://tixxit.files.wordpress.com/2009/12/left-turn.png"><img class="size-thumbnail wp-image-78" title="left-turn" src="http://tixxit.files.wordpress.com/2009/12/left-turn.png?w=150&#038;h=58" alt="" width="150" height="58" /></a><p class="wp-caption-text">p, q, r forming a left turn</p></div>
<p>The heart of the algorithm really lies in finding the furthest right point <em>q</em>, relative to an extreme point <em>p</em>. Say you have 3 points <em>p</em>, <em>q</em> and <em>r</em>. We say <em>p</em>, <em>q</em>, <em>r</em> form a left (respectively right) turn if <em>r</em> lies to the left (right) of the directed line through <em>p</em> and <em>q</em>. We can write a simple function to determine the turn of 3 points:</p>
<p><pre class="brush: python;">
TURN_LEFT, TURN_RIGHT, TURN_NONE = (1, -1, 0)

def turn(p, q, r):
    &quot;&quot;&quot;Returns -1, 0, 1 if p,q,r forms a right, straight, or left turn.&quot;&quot;&quot;
    return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0)
</pre></p>
<p>Finding the furthest right point relative to <em>p</em> just reduces to simply finding the minimum point <em>q</em> using <em>turn</em> with a fixed parameter <em>p</em> as our comparison function. This can is done in <em>O(n)</em> time:</p>
<p><pre class="brush: python;">
def _next_hull_pt(points, p):
    &quot;&quot;&quot;Returns the next point on the convex hull in CCW from p.&quot;&quot;&quot;
    q = points[0] != p and points[0] or points[1]
    for r in (x for x in points if x != p):
        if turn(p, q, r) == TURN_RIGHT:
            q = r
    return q
</pre></p>
<div id="attachment_79" class="wp-caption alignright" style="width: 152px"><a href="http://tixxit.files.wordpress.com/2009/12/degenerate-problem.png"><img class="size-full wp-image-79" title="degenerate-problem" src="http://tixxit.files.wordpress.com/2009/12/degenerate-problem.png?w=655" alt=""   /></a><p class="wp-caption-text">p in between q &amp; r</p></div>
<p>The above function is simple, but it assumes the points are in general position; that there are no 3 collinear points. The first problem arises if there are 2 furthest right points, then we could chose the one that is closer to <em>p</em>, which is not an extreme point (ie. it lies on the hull boundary, but is not a vertex). This becomes a bigger problem if our first comparison relative to this &#8220;mid-point&#8221; is with the 2 vertices on either side of it. We could possibly &#8220;skip&#8221; over the furthest right point, since it is not to the right of the furthest left, but collinear and would end up with the incorrect furthest right point. Luckily, handling this is rather simple; we insist that if there is more than 1 furthest right point, we choose the one furthest from p. We can then rewrite our function, handling this case:</p>
<p><pre class="brush: python;">
def _dist(p, q):
    &quot;&quot;&quot;Returns the squared Euclidean distance between p and q.&quot;&quot;&quot;
    dx, dy = q[0] - p[0], q[1] - p[1]
    return dx * dx + dy * dy

def _next_hull_pt(points, p):
    &quot;&quot;&quot;Returns the next point on the convex hull in CCW from p.&quot;&quot;&quot;
    q = p
    for r in points:
        t = turn(p, q, r)
        if t == TURN_RIGHT or t == TURN_NONE and _dist(p, r) &gt; _dist(p, q):
            q = r
    return q
</pre></p>
<p>The only problem now is finding the first extreme point. This can be done rather simply by choosing the minimum point in <a href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographical order</a>. We can then put this together and simply loop until we end up where we started:</p>
<p><pre class="brush: python;">
def convex_hull(points):
    &quot;&quot;&quot;Returns the points on the convex hull of points in CCW order.&quot;&quot;&quot;
    hull = [min(points)]
    for p in hull:
        q = _next_hull_pt(points, p)
        if q != hull[0]:
            hull.append(q)
    return hull
</pre></p>
<p>We will end up going through <em>h</em> iterations of the loop, where <em>h</em> is the number of points on the convex hull. Each iteration takes <em>O(n)</em> time to find the furthest right point, so the total time required is <em>O(nh)</em>, which is suboptimal. However, it is important to remember that suboptimal does not mean it is useless. The Jarvis March can easily handle very large datasets in memory constrained environments. The only information you need to maintain between iterations is the first and last point found. Finding the next point scans through all points only once; order does not matter. These points could come from a database cursor, for instance. In this case, your function would return an iterator of the hull edges (or points) that generates them <em>on demand</em>, each time next() is called.</p>
<p>You can also <a href="http://gist.github.com/252222">download the complete version of the code.</a> Next post I&#8217;ll cover the Graham Scan.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tixxit.wordpress.com/52/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tixxit.wordpress.com/52/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tixxit.wordpress.com/52/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=52&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tixxit.wordpress.com/2009/12/09/jarvis-march/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b2ecd194174398696f1d9a80bf6a14fa?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tixxit</media:title>
		</media:content>

		<media:content url="http://tixxit.files.wordpress.com/2009/12/left-turn.png?w=150" medium="image">
			<media:title type="html">left-turn</media:title>
		</media:content>

		<media:content url="http://tixxit.files.wordpress.com/2009/12/degenerate-problem.png" medium="image">
			<media:title type="html">degenerate-problem</media:title>
		</media:content>
	</item>
		<item>
		<title>Permutations and Combinations</title>
		<link>http://tixxit.wordpress.com/2009/11/26/permutation/</link>
		<comments>http://tixxit.wordpress.com/2009/11/26/permutation/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 01:23:07 +0000</pubDate>
		<dc:creator>Tom Switzer</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Quite often while programming I find my self going through all possible k-combinations of a list. That is, all possible unordered sets of size k made up of elements of a list. A few times I have needed to iterate through all possible permutations of a list. Getting tired of writing nested for-loops, I wrote [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=1&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Quite often while programming I find my self going through all possible <em>k</em>-combinations of a list. That is, all possible unordered sets of size <em>k</em> made up of elements of a list. A few times I have needed to iterate through all possible permutations of a list. Getting tired of writing nested for-loops, I wrote a small (~40 SLOC) <a title="permute Python module" href="http://github.com/tixxit/permute">Python module to handle combinations (and permutations) of lists</a>. It defines two simple iterators, <strong>combinations</strong> and <strong>permutations</strong> to iterate through <em>k</em>-combinations and permutations of lists.</p>
<p><strong>Combinations:</strong></p>
<p>If you&#8217;ve taken an intro to programming course, you&#8217;ve probably coded something similar to this:</p>
<p><pre class="brush: python;">
def sort(lst, cmp=cmp):
    &quot;&quot;&quot;Sort the list lst.&quot;&quot;&quot;
    for i in xrange(len(lst)):
        for j in xrange(i + 1, len(lst)):
            if lst[j] &lt; lst[i]:
                lst[j], lst[i] = lst[i], lst[j]
</pre></p>
<p>This will sort, in-place, the list lst in <img src='http://s0.wp.com/latex.php?latex=T%28n%29+%3D+%5Cbinom%7Bn%7D%7B2%7D+%3D+%5Cfrac%7Bn%28n-1%29%7D%7B2%7D+%3D+O%28n%5E2%29&amp;bg=333333&amp;fg=eeeeee&amp;s=-2' alt='T(n) = &#92;binom{n}{2} = &#92;frac{n(n-1)}{2} = O(n^2)' title='T(n) = &#92;binom{n}{2} = &#92;frac{n(n-1)}{2} = O(n^2)' class='latex' /> comparisons (ie. not very efficient). However, it illustrates the concepts of combinations. We are actually iterating over all 2-combinations of the set {0,1,..,n-1} (albeit, in a particular order). In this case, we are using the combinations as indices into the list. Now, obviously there are better ways to sort a list, but, though I hate to admit it, I will sometimes brute-force my way to a solution using similar methods (mostly for prototyping or testing more efficient methods for accuracy). For 2-combinations you can just use a loop as above, but what happens when you are going 3 or 4 nested loops deep? Hiding ugly code is never a good thing, but if you gotta do it, you might as well not waste several levels of indentation.</p>
<p>Using the module, we can rewrite the above sorting function as a single for-loop (obviously this still does not change the <img src='http://s0.wp.com/latex.php?latex=O%28n%5E2%29&amp;bg=333333&amp;fg=eeeeee&amp;s=-2' alt='O(n^2)' title='O(n^2)' class='latex' /> time complexity).</p>
<p><pre class="brush: python;">
from permute import combinations
def sort(lst, cmp=cmp):
    &quot;&quot;&quot;Sort list lst.&quot;&quot;&quot;
    for i,j in combinations(range(len(lst)), 2):
        if cmp(a[j], a[i]) &lt; 0:
            a[i], a[j] = a[j], a[i]
</pre></p>
<p>The function has a couple guarantees. First, the type returned by the iterator&#8217;s next function is the same as the type of the list. Second, the function combinations guarantees the order passed to the type constructor will be the same as if you had written <em>k</em> nested for-loops as above&#8230; In other words:</p>
<p><pre class="brush: python;">
x = range(k)
t = type(lst)
for x[0] in xrange(n):
    for x[1] in xrange(x[0] + 1, n):
        ...
        for x[k-1] in xrange(x[k-2] + 1, n):
            v = t(lst[x[i]] for i in xrange(k))
            ...
</pre></p>
<p>Is equivalent to:</p>
<p><pre class="brush: python;">
from permute import combinations
for v in combinations(lst, k):
    ...
</pre></p>
<p><strong>Permutations:</strong></p>
<p>The permutations iterator, as you may have guessed, iterates over all permutations of a list (in lexicographical order). Using this, we can solve the <a href="http://en.wikipedia.org/wiki/Traveling_salesman_problem" target="_self">Travelling Salesman Problem</a>:</p>
<p><pre class="brush: python;">
from permute import *

def solve_tsp(weights):
    nodes = list(reduce(lambda s, e: s.update(e) or s, weights.keys(), set()))
    for i,j in combinations(nodes, 2):
        if (i,j) not in weights and (j,i) not in weights:
            weights[(i,j)] = -1
    path, min = [], -1
    for cand in permutations(nodes):
        dist = 0
        for e in ((cand[i-1], cand[i]) for i in xrange(1, len(nodes))):
            d = e in weights and weights[e] or weights[(e[1], e[0])]
            if d &lt; 0:
                dist = -1
                break
            else:
                dist += d
            if dist &gt;= 0 and (min &lt; 0 or dist &lt; min):
                path, min = cand, dist
    return path, min
</pre></p>
<p>solve_tsp takes 1 argument, a map of edges to their corresponding weights and returns a 2-tuple of the shortest path and its total distance. The &#8220;graph&#8221; (the weight map) is assumed to be undirected. For example,</p>
<p><pre class="brush: python;">
print(solve_tsp({(1,2): 1, (1,3): 2, (1,4): 3, (2,3): 3, (3,4):1}))
</pre></p>
<p>Gives us the shortest path and its total distance: ([2, 1, 3, 4], 4). Going through all permutations (<img src='http://s0.wp.com/latex.php?latex=n%21&amp;bg=333333&amp;fg=eeeeee&amp;s=-2' alt='n!' title='n!' class='latex' />) isn&#8217;t very practical. Once <img src='http://s0.wp.com/latex.php?latex=n&amp;bg=333333&amp;fg=eeeeee&amp;s=-2' alt='n' title='n' class='latex' /> gets larger then you can count on your hands it is really too slow to be of use.</p>
<p>You can <a href="http://github.com/tixxit/permute">grab the permute module from its github repository</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tixxit.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tixxit.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tixxit.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tixxit.wordpress.com&amp;blog=10680490&amp;post=1&amp;subd=tixxit&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://tixxit.wordpress.com/2009/11/26/permutation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b2ecd194174398696f1d9a80bf6a14fa?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tixxit</media:title>
		</media:content>
	</item>
	</channel>
</rss>
