Note that there are some explanatory texts on larger screens.

plurals
  1. POCode-golf: generate pascal's triangle
    text
    copied!<p>Generate a list of lists (or print, I don't mind) a <a href="http://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="noreferrer">Pascal's Triangle</a> of size N with the least lines of code possible!</p> <p>Here goes my attempt (118 characters in <strong>python 2.6</strong> using <a href="http://code.activestate.com/recipes/204297/" rel="noreferrer">a trick</a>):</p> <pre><code>c,z,k=locals,[0],'_[1]' p=lambda n:[len(c()[k])and map(sum,zip(z+c()[k][-1],c()[k][-1]+z))or[1]for _ in range(n)] </code></pre> <p>Explanation:</p> <ul> <li>the first element of the list comprehension (when the length is 0) is <code>[1]</code></li> <li>the next elements are obtained the following way:</li> <li>take the previous list and make two lists, one padded with a 0 at the beginning and the other at the end. <ul> <li>e.g. for the 2nd step, we take <code>[1]</code> and make <code>[0,1]</code> and <code>[1,0]</code></li> </ul></li> <li>sum the two new lists element by element <ul> <li>e.g. we make a new list <code>[(0,1),(1,0)]</code> and map with sum.</li> </ul></li> <li>repeat n times and that's all.</li> </ul> <p>usage (with pretty printing, actually out of the code-golf xD):</p> <pre><code>result = p(10) lines = [" ".join(map(str, x)) for x in result] for i in lines: print i.center(max(map(len, lines))) </code></pre> <p>output:</p> <pre><code> 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload