Search code examples
pythonrecursionpascals-triangle

Pascal's Triangle with Recursion


I need help generating a code that will print Pascal's triangle using recursion.

So far what I've done prints the output "[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1],", etc.

I need my results to print like

1

1 1

1 2 1

1 3 3 1

Each row being a new line of code. Is there any way to split the list so that it prints in that way, or do I need to start over?

Thank you!


Solution

  • You can go like this:

    a = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
    
    for i in a:
        print(" ".join(map(str,i)))
        print() # if you want empty line between the rows.
    

    Prettier like this: (indenting the rows)

    for i,l in enumerate(a):
        print((len(a)-i)*" " +" ".join(map(str,l)))