Welcome, guest | Sign In | My Account | Store | Cart

this script prints a few lines of Pascal`s triangle ;-)

Python, 16 lines
 ``` 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 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

Markus Weihs 16 years, 8 months ago

This one's a little shorter :-) (but less readable :-/)

``````def pascal(n):
l = [[1]]
for i in xrange(n-1):
l.append([1,1])
for j in xrange(len(l[-2])-1):
l[-1].insert(-1,l[-2][j]+l[-2][j+1])
return l

if __name__ == '__main__':
for i in mypascal(20): print i
``````
Markus Weihs 16 years, 8 months ago

In my example above it should be

``````if __name__ == '__main__':
for i in pascal(20): print i
``````
kdsfjkj klfjdsfj 16 years, 8 months ago

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

Scott David Daniels 16 years, 8 months ago

Row by Row. This highlights how the calculation is done.

``````def nextrow(lst):
lag = 0
for element in lst:
yield lag + element
lag = element
yield element

row = [1]
for number in range(12):
row = nextrow(row)
print row
``````
Pood Dov 16 years, 8 months ago

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]

Eduardo gasser 6 years, 5 months ago

Another short solution, with only one loop:

``````def pascal(level):
lst = [1]
while len(lst) < level:
lst = [1] + map(lambda x,y: x+y if y else 1, lst, lst[1:])
print lst

pascal(14)
``````
 Created by DR#m not on Sun, 20 Mar 2005 (PSF)

### Required Modules

• (none specified)