-1

I want to write a function that will take a number (n) and the Pascal's Triangle of it. I have some code written but it doesn't work, it only works for the base case of 1 because it's just an if statement. The code is written here:

def pt_row(n):
  if n == 0:
    return []
  elif n == 1:
    return [1]
  else:
    new_row = [1]
    result = pt_row(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

The code crashes with anything above 2, because "int object do not have a len" or something like that and I can't figure out how to fix it. Here's some test cases:

#What it should do
pt_row(1)
>>> [1]
pt_row(6)
>>> [1, 5, 10, 10, 5, 1]
#What it really does
pt_row(1)
>> [1]
pt_row(6)
CRASH

How do I fix this? Would I just need to turn the variable into a list or would I have to rewrite all the code?

idontcare
  • 29
  • 4
  • 1
    Does this answer your question? [python recursive pascal triangle](https://stackoverflow.com/questions/10628788/python-recursive-pascal-triangle) – Ma0 Mar 03 '20 at 12:48
  • It doesn't that is obviously where I got the code but the code crashes with an number above 1 still. – idontcare Mar 03 '20 at 12:51

1 Answers1

1

result[-1] is an integer, you can't get its len. You just need to return the last row only, so the code can be simplified to:

def pt_row(n):
  if n == 0:
    return []
  elif n == 1:
    return [1]
  else:
    new_row = [1]
    result = pt_row(n-1)
    for i in range(len(result) - 1):
      new_row.append(result[i] + result[i+1])
    new_row += [1]
  return new_row
chuck
  • 1,420
  • 4
  • 19