In [1]:
def pascal(n):
''' Recursive method to print the line of Pascal's triangle. '''
if n == 1:
return [1]
else:
# return the current line wrapped in [1, ..., 1]
curr_line = [1]
prev_line = pascal(n - 1) # recursively find the previous line
for i in range(len(prev_line) - 1):
curr_line.append(prev_line[i] + prev_line[i + 1])
curr_line.append(1)
return curr_line
In [2]:
pascal(2)
Out[2]:
In [3]:
pascal(3)
Out[3]:
In [4]:
pascal(4)
Out[4]:
In [32]:
def pascal2(n):
''' Non recursive version which uses list comprehension. '''
row = [1]
k = [0] # this is needed to allow zip to provide the right tuple
for x in range(max(0,n)):
print(row) # prints the current row
row=[l+r for l,r in zip(row+k,k+row)] # calculate the next row for use in the next iteration
# return row # if we want to return only the last row
In [34]:
pascal2(4)
In [ ]: