Generate a list of lists (or print, I don't mind) a Pascal's Triangle of size N with the least lines of code possible!
Here goes my attempt (118 characters in python 2.6 using a trick):
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)]
Explanation:
- the first element of the list comprehension (when the length is 0) is
[1]
- the next elements are obtained the following way:
- take the previous list and make two lists, one padded with a 0 at the beginning and the other at the end.
- e.g. for the 2nd step, we take
[1]
and make[0,1]
and[1,0]
- e.g. for the 2nd step, we take
- sum the two new lists element by element
- e.g. we make a new list
[(0,1),(1,0)]
and map with sum.
- e.g. we make a new list
- repeat n times and that's all.
usage (with pretty printing, actually out of the code-golf xD):
result = p(10)
lines = [" ".join(map(str, x)) for x in result]
for i in lines:
print i.center(max(map(len, lines)))
output:
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
another stab (python):
Another try, in prolog (I'm practising xD), not too short, just 164c:
explanation:
J, another language in the APL family, 9 characters:
This uses J's builtin "combinations" verb.
Output:
Python: 75 characters
I wrote this C++ version a few years ago:
F#: 81 chars
Explanation: I'm too lazy to be as clever as the Haskell and K programmers, so I took the straight forward route: each element in Pascal's triangle can be uniquely identified using a row n and col k, where the value of each element is
n!/(k! (n-k)!
.