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

Pascal's triangle was a challenge on a forum I frequent today and this is what I came up with:

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def pascals_triangle(n):
    '''
    Pascal's triangle:

    for x in pascals_triangle(5):
        print('{0:^16}'.format(x))

          [1]       
         [1, 1]     
       [1, 2, 1]    
      [1, 3, 3, 1]  
    [1, 4, 6, 4, 1]
    '''
    x=[[1]]
    for i in range(n-1):
        x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
    return x

4 comments

Michael Puckett (author) 13 years, 2 months ago  # | flag

Even better:

def pascals_triangle(n):
    x=[[1]]
    for i in range(n-1):
        x.append(list(map(sum,zip([0]+x[-1],x[-1]+[0]))))
    return x
Paddy McCarthy 13 years, 2 months ago  # | flag

The second doesn't even look triangular :-)

Mh 13 years, 1 month ago  # | flag

maybe you also like

pascals_triangle=lambda n:[[i for i in str(11**j)] for j in range(n)]
Mh 13 years, 1 month ago  # | flag

for sure it works just for ´n<6´ since it would cut the ´10´ to ´1, 0´ etc.

Created by Michael Puckett on Fri, 14 Jan 2011 (MIT)
Python recipes (4591)
Michael Puckett's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks