Question:
Python recursive function pascal triangle wont display?
Matt
2013-07-24 16:57:54 UTC
Hi all,

I am trying to run my program which is a recursive function however im not sure how to run it(Total noob here) I run the program then the shell comes up and you can type whatever... doesn't show anything??? Please help...

This is the question im working on:
Create a program which with a function that implements Pascal's triangle. (Note: This will require you to use a recursive function!)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

This is the code I have so far:
def triangle(n):
if n == 0:
return []
elif n == 1:
return [[1]]
else:
new_row = [1]
result = triangle(n-1)
last_row = result[-1]
for i in range(len(last_row)-1):
new_row.append(last_row[i] + last_row[i+1])
new_row += [1]
result.append(new_row)
return result

Thanks for your help!!!
Three answers:
anonymous
2013-07-28 03:46:27 UTC
ou just need to pass a list of lists through the recursion, and pick off the last element of the list (i.e. the last row of the triangle) to build your new row. Like so:

def triangle(n):

if n == 0:

return []

elif n == 1:

return [[1]]

else:

new_row = [1]

result = triangle(n-1)

last_row = result[-1]

for i in range(len(last_row)-1):

new_row.append(last_row[i] + last_row[i+1])

new_row += [1]

result.append(new_row)

return result
?
2016-11-06 02:44:55 UTC
Python Recursive Function
anonymous
2016-05-20 07:35:52 UTC
def foo(n): ----if(n == 0): --------return 0; ----n + foo(--n); I think ^^


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...