Bill Mill http://www.billmill.org/ Visualizing Permutations http://billmill.org/permvis.html http://billmill.org/permvis.html Thu, 29 Apr 2010 21:10:00 +0000 <p>At some point a few years ago, I got interested in permutation algorithms and implemented a few that were in Knuth as well as gathered some that were floating around the internet. I never did anything with them, until I saw Aldo Cortesi's excellent <a href="http://corte.si/posts/code/visualisingsorting/index.html">sorting visualizations</a> which reminded me of <a href="http://img.skitch.com/20100429-muthj97xmh8a34dnwnqkc64d6e.jpg">a figure from Knuth</a>, and inspired me to create some visualizations of my own using Aldo's code. <p><h2>Lexicographic Permutations</h2> <p>Informally, the permutations of a set are all possible orderings of its members. The permutations of the set <i>{1,2,3}</i>, are: <p><code>[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]</code> <p>This particular ordering of permutations is in <i>lexicographic order</i>; it's listed in the same order as it would be in the dictionary. There are many well-known algorithms for generating permutations in lexicographic order. <a href="http://github.com/llimllib/personal_code/blob/master/python/permutation/permute.py#L5">Here</a> is my version of one such algorithm; <a href="http://www-cs-faculty.stanford.edu/~knuth/fasc2b.ps.gz">go read Knuth</a> if you're at all interested in learning more. <p>Here's what a lexicographic permutation of four elements looks like: <p><img src="http://billmill.org/static/perm1.png"> <p>It's easy to see that each element gets its turn at the top of the list, and that each time a new element goes to the top the remainder of the list is sorted. <p><h2>Single-transposition Permutations</h2> <p>It is an interesting and non-obvious fact that there's a way to permute any given set by only switching the positions of one pair of elements per iteration. This permutation is deeply related to the <a href="http://en.wikipedia.org/wiki/Gray_code">Gray code</a>, which if you haven't heard of, I highly recommend you go read about. The Knuth <a href="http://www-cs-faculty.stanford.edu/~knuth/fasc2b.ps.gz">paper</a> I mentioned aleady has a superb bit on the Gray code. <p><img src="http://billmill.org/static/perm4.png"> <p>This image demonstrates clearly that at each step, there is exactly one crossing. My implementation of this algorithm is <a href="http://github.com/llimllib/personal_code/blob/master/python/permutation/permute.py#L201">also on github.</a> <p><h2>CLP Permutation</h2> <p>I know very little about this algorithm, except that I got it from <a href="http://mail.python.org/pipermail/python-list/2002-November/170393.html">a message to comp.lang.python</a> where it's attributed to Alex Martelli, Duncan Smith, and somebody named Anton (Anton Vredegoor?). Despite the crazy number of switches, and the fact that it reorders the list it's passed, it's actually crazy fast. <p><img src="http://billmill.org/static/clp_perm.png"> <p>I'd love to hear from anyone with more info on this algorithm; my slightly modified version is <a href="http://github.com/llimllib/personal_code/blob/master/python/permutation/permute.py#L233">here</a>. <p><h2>Odds and Ends</h2> <p>Well, that's it, just wanted to post some fun pictures of permutations, I hope you enjoyed it. The code I used to generate the pictures is derived from Aldo Cortesi's wonderful <a href="http://github.com/cortesi/sortvis">sortvis</a>, and all my modifications to it are <a href="http://github.com/llimllib/personal_code/tree/master/python/permvis">available on github</a> as well. <p>If you want bonus points, I never got around to implementing Knuth's algorithm E (it's given towards the end of <a href="http://www-cs-faculty.stanford.edu/~knuth/fasc2b.ps.gz">this</a>), and I'd love for somebody else to do my work for me. If you're tough enough, that is. Visualizing Permutations The Bill Mill NCAA Bracket Randomizer, 2010 edition http://billmill.org/ncaa_randomizer_2010.html http://billmill.org/ncaa_randomizer_2010.html Sun, 14 Mar 2010 20:15:00 +0000 <p>I've updated my <a href="http://billmill.org/ncaa_randomizer.html">NCAA bracket randomizer</a> for the 2010 field; check it out <a href="http://billmill.org/static/ncaa-bracket-randomizer/out.html">here</a>. As of now, there are no improvements, but those may come in the next few days; feel free to suggest ideas. The Bill Mill NCAA Bracket Randomizer, 2010 edition Multi-Line Lambdas in Python Using the With Statement http://billmill.org/multi_line_lambdas.html http://billmill.org/multi_line_lambdas.html Thu, 20 Aug 2009 22:55:00 +0000 <p>Python <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=147358">does not have multi-line lambdas</a> because Guido dislikes them aesthetically. However, with just a bit of introspection, code like this is possible: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #666666">&gt;&gt;&gt;</span> <span style="color: #007020; font-weight: bold">with</span> each([<span style="color: #40a070">12</span>, <span style="color: #40a070">14</span>, <span style="color: #40a070">16</span>]): <span style="color: #666666">...</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(x): <span style="color: #666666">...</span> <span style="color: #007020; font-weight: bold">print</span> x <span style="color: #666666">...</span> <span style="color: #007020; font-weight: bold">print</span> x<span style="color: #666666">+</span><span style="color: #40a070">1</span> <span style="color: #666666">...</span> <span style="color: #40a070">12</span> <span style="color: #40a070">13</span> <span style="color: #40a070">14</span> <span style="color: #40a070">15</span> <span style="color: #40a070">16</span> <span style="color: #40a070">17</span> </pre></div> <p>I'll say a bit about my motivation for creating code like this, show how easy it is to write, and then I'll argue that code like this is both pythonic and aesthetically appealing in some circumstances. <p><h2>A Mystery Solved (By Holmes Himself!)</h2> <p>When I first saw code using the <code>with</code> statement, my hope was that it would be able to be used somewhat like Haskell's <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29#More_complex_examples">Where clause</a> or Ruby's <a href="http://allaboutruby.wordpress.com/2006/01/20/ruby-blocks-101/">blocks</a>. When I dug into the <a href="http://www.python.org/dev/peps/pep-0343/">spec</a>, I was disappointed to discover that if it was possible, it wasn't easy, and I pushed the thought aside. <p>That was a couple years ago, and I didn't give it a moment's thought until I saw <a href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.3">a blog post</a> by Richard Jones that uses a <code>with</code> statement in exactly the way I had considered impossible up to now. I spent a few hours trying to figure it out, but I was stumped, so I put up <a href="http://stackoverflow.com/questions/1255914/finding-functions-defined-in-a-with-block">a question</a> on Stack Overflow to see if somebody could show me how he did it. <p>Within a few hours, <a href="http://en.wikipedia.org/wiki/Alex_Martelli">Alex Martelli</a> himself chimed in with a wonderful solution. The gist of the answer is that you can use the <code>inspect</code> module to access the <a href="http://www.python.org/doc/2.5.2/lib/typecontextmanager.html">context manager</a>'s calling scope, and figure out what variables have been defined between its <code>__enter__</code> and <code>__exit__</code> functions. I'm glad I asked aloud, because even if I had stumbled close to the solution, I surely wouldn't have come up with one as complete as his. <p><h2>The How</h2> <p>Once I had Alex's proof of concept code in hand, I went to work making it do what I'd had in my head so long ago. In about an hour, I was able to write code that looks like this: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #555555; font-weight: bold">@accepts_block</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">each</span>(iterable, block): <span style="color: #007020; font-weight: bold">for</span> i <span style="color: #007020; font-weight: bold">in</span> iterable: block(i) <span style="color: #007020; font-weight: bold">with</span> each([<span style="color: #4070a0">&quot;twelve&quot;</span>, <span style="color: #4070a0">&quot;fourteen&quot;</span>, <span style="color: #4070a0">&quot;sixteen&quot;</span>]): <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(x): <span style="color: #007020; font-weight: bold">print</span> x <span style="color: #555555; font-weight: bold">@accepts_block</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">bmap</span>(arr, block): <span style="color: #007020; font-weight: bold">return</span> <span style="color: #007020">map</span>(block, arr) <span style="color: #007020; font-weight: bold">with</span> bmap([<span style="color: #40a070">1</span>,<span style="color: #40a070">2</span>,<span style="color: #40a070">3</span>]) <span style="color: #007020; font-weight: bold">as</span> foo: <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(x): <span style="color: #007020; font-weight: bold">return</span> (<span style="color: #007020">float</span>(x) <span style="color: #666666">+</span> <span style="color: #40a070">1</span>) <span style="color: #666666">/</span> <span style="color: #40a070">2</span> <span style="color: #007020; font-weight: bold">print</span> foo <span style="color: #60a0b0; font-style: italic"># [1.0, 1.5, 2.0]</span> </pre></div> <p>What you see above are two functions which use a decorator giving them access to the function defined within the <code>with</code> block. The decorator passes the block to the function as its last argument just <a href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/">like in Ruby</a>. <p>To understand how this happens, you need to know how context managers work. Context managers consist of a class with <code>__enter__</code> and <code>__exit__</code> methods which are called upon entering the with block and upon exiting, just as you'd expect. <p>Alex's solution involves scanning the scope of the calling function from the <code>__enter__</code> and <code>__exit__</code> methods, and pulling out the differences between them. These differences will be all the variables that were defined in the <code>with</code> block. A sketch: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">class</span> <span style="color: #0e84b5; font-weight: bold">FindInteresting</span>(<span style="color: #007020">object</span>): <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__enter__</span>(<span style="color: #007020">self</span>): f <span style="color: #666666">=</span> inspect<span style="color: #666666">.</span>currentframe(<span style="color: #40a070">1</span>) <span style="color: #007020">self</span><span style="color: #666666">.</span>already_defined <span style="color: #666666">=</span> <span style="color: #007020">dict</span>(f<span style="color: #666666">.</span>f_locals) <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__exit__</span>(<span style="color: #007020">self</span>): f <span style="color: #666666">=</span> inspect<span style="color: #666666">.</span>currentframe(<span style="color: #40a070">1</span>) <span style="color: #60a0b0; font-style: italic">#pick out the differences between f.f_locals and self.already_defined</span> </pre></div> <p>When we pick out the differences between the two, we need to be careful to check for names that have been redefined so that we don't miss out on new functions that reuse old names. <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__exit__</span>(<span style="color: #007020">self</span>): f <span style="color: #666666">=</span> inspect<span style="color: #666666">.</span>currentframe(<span style="color: #40a070">1</span>) interesting <span style="color: #666666">=</span> {} <span style="color: #007020; font-weight: bold">for</span> n <span style="color: #007020; font-weight: bold">in</span> f<span style="color: #666666">.</span>f_locals: newf <span style="color: #666666">=</span> f<span style="color: #666666">.</span>f_locals[n] <span style="color: #007020; font-weight: bold">if</span> n <span style="color: #007020; font-weight: bold">not</span> <span style="color: #007020; font-weight: bold">in</span> <span style="color: #007020">self</span><span style="color: #666666">.</span>already_defined: interesting[n] <span style="color: #666666">=</span> newf <span style="color: #007020; font-weight: bold">continue</span> anf <span style="color: #666666">=</span> <span style="color: #007020">self</span><span style="color: #666666">.</span>already_defined[n] <span style="color: #007020; font-weight: bold">if</span> <span style="color: #007020">id</span>(newf) <span style="color: #666666">!=</span> <span style="color: #007020">id</span>(anf): interesting[n] <span style="color: #666666">=</span> newf </pre></div> <p>After this function has run, <code>interesting</code> is a dictionary which (probably) contains all the names and values of the variables that have been redefined in the <code>with</code> block. <p>Because we have to use the <code>id</code> check to determine if a name has been redefined, and Python sometimes caches objects in memory, our function can be fooled. In this case, <code>interesting</code> will not detect <code>x</code> because it's being redefined and cpython caches the low integers, so <code>id(x)</code> will be the same for both <code>x</code>s. <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%">x <span style="color: #666666">=</span> <span style="color: #40a070">1</span> <span style="color: #007020; font-weight: bold">with</span> FindInteresting: x <span style="color: #666666">=</span> <span style="color: #40a070">1</span> </pre></div> <p>In general, the cpython runtime is not aggressive about caching, but you should know that this possibility exists. If you use this technique, I recommend being strict about checking only newly defined functions, since there's no way to be sure if you missed any redefined names. <p>To make the teaser code at the top of the article work, I just wrapped Alex's code into a decorator that returned a context manager, then called the function being decorated with the definitions that we found in the <code>interesting</code> dictionary. The context manager's <code>__call__</code> function gets overridden to allow you to pass in arguments for the function being decorated. <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">accepts_block</span>(f): <span style="color: #007020; font-weight: bold">class</span> <span style="color: #0e84b5; font-weight: bold">BlockContextManager</span>(<span style="color: #007020">object</span>): <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__call__</span>(<span style="color: #007020">self</span>, <span style="color: #666666">*</span>args, <span style="color: #666666">**</span>kwargs): <span style="color: #007020">self</span><span style="color: #666666">.</span>thefunction <span style="color: #666666">=</span> functools<span style="color: #666666">.</span>partial(f, <span style="color: #666666">*</span>args, <span style="color: #666666">**</span>kwargs) <span style="color: #007020; font-weight: bold">return</span> <span style="color: #007020">self</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__enter__</span>(<span style="color: #007020">self</span>): <span style="color: #60a0b0; font-style: italic">#do Alex&#39;s magic, just as above</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__exit__</span>(<span style="color: #007020">self</span>): <span style="color: #60a0b0; font-style: italic">#make the interesting dictionary, just as above</span> <span style="color: #007020; font-weight: bold">if</span> <span style="color: #007020">len</span>(interesting) <span style="color: #666666">==</span> <span style="color: #40a070">1</span>: block <span style="color: #666666">=</span> <span style="color: #007020">list</span>(interesting<span style="color: #666666">.</span>itervalues())[<span style="color: #40a070">0</span>] <span style="color: #007020; font-weight: bold">assert</span> <span style="color: #007020">isinstance</span>(block, <span style="color: #007020">type</span>(<span style="color: #007020; font-weight: bold">lambda</span>:<span style="color: #007020">None</span>)) <span style="color: #007020">self</span><span style="color: #666666">.</span>thefunction(block) <span style="color: #007020; font-weight: bold">return</span> BlockContextManager() </pre></div> <p>It looks complicated and nested, but all it's doing is saving the function and all its arguments, grabbing the definitions from the with block, making sure there's only one definition and it's a function, then tacking it onto the end of the arguments list for the function and calling it. Phew. <p>The code above handles the case where you don't need to store the result of the function being decorated: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #555555; font-weight: bold">@accepts_block</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">each</span>(iterable, block): <span style="color: #007020; font-weight: bold">for</span> i <span style="color: #007020; font-weight: bold">in</span> iterable: block(i) </pre></div> <p>But what if we want to store the result? Turns out, we can further abuse the <code>with</code> block by hijacking its <code>as</code> clause. Because a variable defined in the <code>as</code> clause gets detected by Alex's code, we can use the inspect module to change that variable so that after the with block it reflects the result of our computation. <p>First we check to see if we probably have a block and a variable in the as statement, then we reach in and store our result there if we are in that case: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">__exit__</span>(<span style="color: #007020">self</span>): <span style="color: #60a0b0; font-style: italic">#exactly as before; frame = inspect.currentframe(1)</span> <span style="color: #007020; font-weight: bold">if</span> <span style="color: #007020">len</span>(interesting) <span style="color: #666666">==</span> <span style="color: #40a070">1</span>: <span style="color: #60a0b0; font-style: italic">#exactly the same as before</span> <span style="color: #007020; font-weight: bold">elif</span> <span style="color: #007020">len</span>(interesting) <span style="color: #666666">==</span> <span style="color: #40a070">2</span>: block <span style="color: #666666">=</span> <span style="color: #007020">None</span> savename <span style="color: #666666">=</span> <span style="color: #007020">None</span> <span style="color: #007020; font-weight: bold">for</span> n,v <span style="color: #007020; font-weight: bold">in</span> interesting<span style="color: #666666">.</span>iteritems(): <span style="color: #007020; font-weight: bold">if</span> <span style="color: #007020">isinstance</span>(v, <span style="color: #007020">type</span>(<span style="color: #007020; font-weight: bold">lambda</span>:<span style="color: #007020">None</span>)): block <span style="color: #666666">=</span> v <span style="color: #007020; font-weight: bold">else</span>: savename <span style="color: #666666">=</span> n <span style="color: #007020; font-weight: bold">assert</span> savename <span style="color: #007020; font-weight: bold">and</span> <span style="color: #007020">isinstance</span>(block, <span style="color: #007020">type</span>(<span style="color: #007020; font-weight: bold">lambda</span>:<span style="color: #007020">None</span>)) frame<span style="color: #666666">.</span>f_locals[savename] <span style="color: #666666">=</span> <span style="color: #007020">self</span><span style="color: #666666">.</span>thefunction(block) </pre></div> <p>Which lets us do this: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #555555; font-weight: bold">@accepts_block</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">bmap</span>(iterable, block): <span style="color: #007020; font-weight: bold">return</span> <span style="color: #007020">map</span>(block, iterable) <span style="color: #007020; font-weight: bold">with</span> bmap([<span style="color: #40a070">1</span>,<span style="color: #40a070">2</span>,<span style="color: #40a070">3</span>]) <span style="color: #007020; font-weight: bold">as</span> result: <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(x): <span style="color: #007020; font-weight: bold">return</span> x<span style="color: #666666">**</span><span style="color: #40a070">2</span> <span style="color: #007020; font-weight: bold">print</span> result <span style="color: #60a0b0; font-style: italic">#[1,4,9]</span> </pre></div> <p>This time, we're really taking a leap by assuming that if we find a callable and any other variable, that the variable is where we want to store our results. This can lead to somewhat unexpected results: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">with</span> bmap([<span style="color: #40a070">1</span>,<span style="color: #40a070">2</span>,<span style="color: #40a070">3</span>]): not_a_result <span style="color: #666666">=</span> <span style="color: #40a070">12</span> <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(x): <span style="color: #007020; font-weight: bold">return</span> x<span style="color: #666666">**</span><span style="color: #40a070">2</span> <span style="color: #007020; font-weight: bold">print</span> not_a_result <span style="color: #60a0b0; font-style: italic"># [1,4,9] instead of 12</span> </pre></div> <p>That's my extremely long-winded description of how to abuse the with operator. If you want to see the full function and the super-lame test code I wrote, you can <a href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master">head on over to github</a> and check it out. <p><h2>Aesthetics</h2> <p>It should be clear from all of the disclaimers I've had to put into this article that this technique is of limited use in Python as it stands today. I'd like to make an argument that it suggests some nice syntactic sugar for python to support someday, while remaining totally ignorant of the actual difficulties of putting it into the language. <p>To do so, I'll start by posting the motivating example for decorators from <a href="http://www.python.org/dev/peps/pep-0318/">the relevant PEP</a>. It argues that this code: <p><div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">foo</span>(cls): <span style="color: #007020; font-weight: bold">pass</span> foo <span style="color: #666666">=</span> synchronized(lock)(foo) foo <span style="color: #666666">=</span> <span style="color: #007020">classmethod</span>(foo) </pre></div> is not nearly as readable as this code: <p><div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #555555; font-weight: bold">@classmethod</span> <span style="color: #555555; font-weight: bold">@synchronized</span>(lock) <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">foo</span>(cls): <span style="color: #007020; font-weight: bold">pass</span> </pre></div> <p>The main problem with the readability of the first snippet is not that it requires 2 redefinitions and 4 repetitions of <code>foo</code>. Rather, the main problem is that it places the cart before the horse by putting the function body ahead of the declarations that are required to understand it. <p>Similarly, when we define callback functions before we use them, we're required to define the function body before the place where it will be actually used. Often, we see: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">handle_click</span>(<span style="color: #007020">self</span>): foo <span style="color: #666666">=</span> <span style="color: #007020">self</span><span style="color: #666666">.</span>flim() <span style="color: #007020; font-weight: bold">if</span> foo: <span style="color: #007020">self</span><span style="color: #666666">.</span>flam(foo) onClick(handle_click) </pre></div> <p>When it would be clearer to write: <div class="highlight" style="background: #f0f0f0"><pre style="line-height: 125%"><span style="color: #007020; font-weight: bold">with</span> onClick(): <span style="color: #007020; font-weight: bold">def</span> <span style="color: #06287e">_</span>(<span style="color: #007020">self</span>): foo <span style="color: #666666">=</span> <span style="color: #007020">self</span><span style="color: #666666">.</span>flim() <span style="color: #007020; font-weight: bold">if</span> foo: <span style="color: #007020">self</span><span style="color: #666666">.</span>flam() </pre></div> <p>Which I find much more appealing. <p><h2>Conclusion</h2> <p>I expect that there's no way that syntax like this could be officially supported by Python, both because of syntactic constraints and the <acronym="Benevolent Dictator For Life">BDFL</a>'s aesthetic concerns. I do think it is a neat exercise in pushing the Python interpreter and syntax past where they want to go, and I hope that it gives some food for thought on an interesting Python syntax. <p>I'm excited to see where Richard Jones goes with his <a href="http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.7">project</a>, and the design choices that he makes in it, since he's pushing the boundaries of Python design. Many thanks to him and Alex Martelli for sending me down quite an enjoyable path. <p>Finally, in case you missed it above, go ahead and <a href="http://github.com/llimllib/Python-Multiline-Lambdas/tree/master">take a look at the code</a> on github. <p>If you want to leave a comment, I suggest leaving it on <a href="http://www.reddit.com/r/Python/comments/9cnaw/multiline_lambdas_in_python_using_the_with/">reddit</a>. <p><h2>Update:</h2> Someone <a href="http://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython?ts=1253546882&updated=AnonymousBlocksInPython">has</a> taken this technique a bit farther, using some bytecode hackery. Multi-Line Lambdas in Python Using the With Statement What Gladwell is Missing: Institutional Memory http://billmill.org/institutional_memory.html http://billmill.org/institutional_memory.html Sun, 31 May 2009 16:50:00 +0000 <p>Malcolm Gladwell's recent <a href="http://www.newyorker.com/reporting/2009/05/11/090511fa_fact_gladwell?yrail">article</a>, ostensibly about how Davids can beat Goliaths, featured great praise for the full-court press as a method for less-skilled teams to beat more-skilled ones. He writes: <blockquote>In the world of basketball, there is one story after another like this about legendary games where David used the full-court press to beat Goliath. Yet the puzzle of the press is that it has never become popular. People look at upsets like Fordham over UMass and call them flukes. Basketball sages point out that the press can be beaten by a well-coached team with adept ball handlers and astute passers&mdash;and that is true... Playing insurgent basketball did not guarantee victory. It was simply the best chance an underdog had of beating Goliath.</blockquote> <p>After his piece was <a href="http://galleyslaves.blogspot.com/2009/05/more-on-gladwell-press-etc.html">rightly</a> <a href="http://deadspin.com/5239721/malcolm-gladwell-wants-to-know-why-your-team-doesnt-press-more">criticized</a> <a href="http://rivals.yahoo.com/ncaa/basketball/blog/the_dagger/post/Malcolm-Gladwell-still-talking-about-the-full-co?urn=ncaab,163209">all</a> <a href="http://rushthecourt.net/2009/05/05/gladwells-theory-on-full-court-pressure-is-the-only-outlier-here/">over</a> <a href="http://www.nbcnewyork.com/sports/basketball/Why-Dont-More-Basketball-Teams-Run-the-Press.html">the</a> <a href="http://nymag.com/daily/intel/2009/05/malcolm_gladwell_isnt_a_basket.html">web</a>, ESPN <a href="http://sports.espn.go.com/espn/page2/story?page=simmons/090513">published</a> a long and interesting email conversation between him and Bill Simmons that addressed the criticism. In it, Gladwell defended his column: <blockquote>After my piece ran in <em>The New Yorker</em>, one of the most common responses I got was people saying, well, the reason more people don't use the press is that it can be beaten with a well-coached team and a good point guard. That is (A) absolutely true and (B) beside the point. The press doesn't guarantee victory. It simply represents the underdog's best chance of victory&hellip; I went to see a Lakers-Warriors game earlier this season, and it was abundantly clear after five minutes that the Warriors' chances of winning were, oh, no better than 10 percent. Why wouldn't you have a special squad of trained pressers come in for five minutes a half and press Kobe and Fisher?&hellip; Best case is that you rattle the Lakers and force a half-dozen extra turnovers that turn out to be crucial. And if you lose, so what? You were going to lose anyway.</blockquote> <p>Although lots of people have responded to this rebuttal, I haven't seen anyone mention what I consider to be an important reason that many teams have chosen not to implement full-court presses: <strong>Institutional Memory</strong>. <p>Let's imagine that the Warriors had in fact, put on the press, and that it had worked. The Warriors won against the vaunted Lakers! How would the team respond? They would press more. When that worked to win some more games, they would probably trade some of their players who were less well suited to the press to make room for some younger, faster, fitter players. They would win a few more games than they had been before. Everything's going good, right? <p>Then they hit a snag; <strong>No team has won the NBA Championship by pressing </strong>. The Warriors could optimize like crazy for the press, but they'd be training and working and trading and drafting to be, at best, a pretty good team. But no NBA team wants to be a pretty good team&mdash;they all want to win championships. <p>The mental exercise reveals what Gladwell has missed: the Warriors aren't playing to win that game, or even the most games that season. They're playing to try and win an NBA championship, and to do so, they need to spend years trying to build up the institutional memory of how to win games in the traditional way so that they can eventually beat every team, not just to win more games than they did playing traditionally. <p>All of this leads to a simple admonishment when analyzing organizations: don't expect that the organization is optimizing for what you think they're optimizing for. And when an organization seems to be acting in ways that are surprising to you, look for metrics that may be more important to them than the ones you expect. What Gladwell is Missing: Institutional Memory The Bill Mill NCAA Bracket Randomizer http://billmill.org/ncaa_randomizer.html http://billmill.org/ncaa_randomizer.html Wed, 18 Mar 2009 16:00:00 +0000 <p>Each year, when the NCAA basketball tournament comes around, I end up in four or five pools, with a separate bracket filled out for each. I love the games, and I love having teams to root for, but I really hate the process of guessing to fill out my brackets. I inevitably pick too many upsets, just because I want to have fun rooting for underdogs; instead I end up bored after the first two rounds. <p>This year, I thought I could write some software to help me pick out my brackets. If I let the computer pick reasonably but randomly for each pool, I figure that I stand a better chance of having <em>one</em> decent bracket instead of the assortment of crappy ones I normally end up with. <p>So the last two nights, I <a href="http://billmill.org/static/ncaa-bracket-randomizer/out.html">wrote myself a bracket randomizer</a>; just push the "randomize" button at the top and watch it go. <p>In order to pick what team will win a given game, it first calculates the chance each team will win by plugging <a href="http://kenpom.com/rate.php">Ken Pomeroy's</a> ratings into the <a href="http://www.diamond-mind.com/articles/playoff2002.htm">log5</a> formula. Then it picks a random number and compares it to the probability of the favorite winning; if the number is lower than that, it advances the favorite. Otherwise, it advances the underdog. Rinse and repeat, and you should have a reasonable random bracket for the whole tournament. <h2>The Output</h2> <p>Next to each team in the bracket, you'll see three numbers in parentheses. These numbers represent, respectively, the team's Pythagorean rating, adjusted offensive efficiency, and adjusted defensive efficiency. <p>If that's Greek to you (<em>groan</em>), go check out <a href="http://www.kenpom.com/blog/index.php/weblog/ratings_explanation/">Ken's explanation</a> of what that means. <p>The color of each team, once you've randomized, represents their odds of winning. Brighter green is more of a favorite, deeper red more of an underdog. It should update the colors if you manually change the teams, but it won't; I just didn't have time to get everything done that I wanted to. Similarly, it won't update future games if you change the winner of an early one. <h2>The Code</h2> <p>The surprisingly difficult part of this project was creating a simple HTML bracket that looked reasonable and allowed you to click to advance a team. I didn't get everything into the page that I wanted to, simply because I spent so much time just getting that done. (Keep in mind we're talking about a 2-night hack here). <p>The code to generate the bracket is contained in one super-ugly <a href="http://github.com/llimllib/ncaa-bracket-randomizer/blob/1db753ce4f91fc84265efa6a27fa7ee00e84eaa2/bracket.py">python file</a>. <p>If you've got ideas for stuff to add, or want to generate a cooler looking bracket, or just check out the code, you can <a href="http://github.com/llimllib/ncaa-bracket-randomizer/tree/master">go get it</a> at github. Feel free to fork and enjoy! The Bill Mill NCAA Bracket Randomizer