Search code examples
pythonpython-3.xfor-looptuplespascals-triangle

Python: printing 1 row of Pascal Triangle


New to learning python and am having some trouble understanding a solution provided? It has to do with Pascal Triangle and printing the rows when asking a user to "enter a row number"

There were bits of the solution provided and the rest I fit in (first for loop)..

n=int(input("Enter a row number: "))
a=[]
for i in range(n):
    a.append([])
    a[i].append(1)
    for j in range(1,i):
        a[i].append(a[i-1][j-1]+a[i-1][j])
    if(n!=0):
        a[i].append(1)
for i in range(n):
    print("   "*(n-i),end=" ",sep=" ")
    for j in range(0,i+1):
        print('{:4}'.format(a[i][j]),end=" ")
    print()

My question is which part of the code is printing the triangle structure? I assume the last for loop? Also if I wanted to just print 1 row, what would I be changing? EX: Input: 5 and output would be [1 4 6 4 1 ]

Thank you and any help/advice would be appreciated


Solution

  • You are right, the last loop is printing every row of the triangle. To print any specific row, jut run the second loop with specific value of i.

    Before that, there is an easier way to more forward. Let's consider the output of below code:

    n = 7
    a = []
    for i in range(n):
        a.append([])
        a[i].append(1)
        for j in range(1, i):
            a[i].append(a[i - 1][j - 1] + a[i - 1][j])
        if (n != 0):
            a[i].append(1)
    
    print(a)
    

    The output is:

    [[1, 1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1]]
    

    From this 2d array, you can decide which single element you want to print. For example at index 4 you have [1, 4, 6, 4, 1]. From these values in the array a you can figure out which row to print.

    Now for 5 if you want [1, 4, 6, 4, 1], you can simply do the following:

    n = 7
    a = []
    for i in range(n):
        a.append([])
        a[i].append(1)
        for j in range(1, i):
            a[i].append(a[i - 1][j - 1] + a[i - 1][j])
        if (n != 0):
            a[i].append(1)
    
    to_print = 5
    for i in range(0, len(a[to_print-1])):
        print(a[to_print-1][i], end=" ")
    

    The output will be:

    1 4 6 4 1