Today I challenged myself to try and implement a recursive function that would produce Pascal's Triangle up to n levels. I managed to come up with a solution, however, it is not as efficient or elegant as I would like. In the following code, each time I call pascal_row() in pascal(), it has iterate through whatever number of levels is passed to pascal_row(); opposed to having it go through and build the triangle in n levels. I don't know if that makes sense, but here is the code... is there anyway to optimize this?
#builds the pascal row for the specified level
#ex. pascal_row(3) --> [1,3,3,1]
def pascal_row(levels):
if levels == 0:
return [1]
elif levels == 1:
return [1,2,1]
else:
row = []
row.append(1)
prev = pascal_row(levels-1)
for i in range(len(prev)):
try:
row.append(prev[i] + prev[i+1])
except:
pass
row.append(1)
return row
#prints out pascal triangle up to specified level
def pascal(levels):
for lvl in range(levels):
print(pascal_row(lvl))
if __name__ == "__main__":
pascal(10) #outputs correctly