this script prints a few lines of Pascal`s triangle ;-)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def pascal(n):
"""Prints n first lines of Pascal`s triangle
author: DR#m <dnpsite.narod.ru>
last rev 20.03.05"""
l=[1]
p=[]
for i in xrange(n):
l2=[1]
for j in xrange(len(l)-1):
l2.append(l[j]+l[j+1])
l2.append(1)
print l
l=l2
if __name__=="__main__":
pascal(20)
|
anyone going beat this? thak you
Tags: algorithms
This one's a little shorter :-) (but less readable :-/)
In my example above it should be
Shorter? Take this. def pascal2(n, t=[1], z=[[1]]): for i in xrange(1, n): z+=[[1]+[z[i-1][j]+z[i-1][j+1] for j in range(len(z[i-1])-1)]+[1]] print z
Row by Row. This highlights how the calculation is done.
Another try. def pas(n=10): line=[1] for i in range(0,n): print line line=[0]+line for j in range(len(line)-1): line[j]+=line[j+1]
Another short solution, with only one loop: