After completing a task to create a pascal triangle using an iterative function, I tried to recreate it using a recursive function. I went so far as to make him create a separate line corresponding to the number passed as an argument. But several attempts to get him to create the entire triangle down to this line, including this line, failed. I even tried writing a separate function that iterates over the range of the input number and calls a recursive function with a repeated digit, adding separate lines for the list before returning this list. The desired result should be a list in which each internal list contains one line of the triangle. For instance:
[[1], [1, 1], [1, 2, 1]...]
Instead, it returns the messy mess of the nested list, completely populated with 1st.
Here is the recursive function in question, without a second function to add rows (I still need 1 all-encompassing function):
def triangle(n):
if n == 0:
return []
elif n == 1:
return [1]
else:
new_row = [1]
last_row = triangle(n-1)
for i in range(len(last_row)-1):
new_row.append(last_row[i] + last_row[i+1])
new_row += [1]
return new_row
To be clear, I have already completed the assigned task, this is just for a deeper understanding of recursion ...
Iterative solution:
def triangle(n):
result = []
for row in range(n):
newrow = [1]
for col in range(1, row+1):
newcell = newrow[col-1] * float(row+1-col)/col
newrow.append(int(newcell))
result.append(newrow)
return result
source
share