1

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

  • Please assign a fixed value to `n`, e.g. `n=5`, ideally do the same for `a`. Also please provide the output of your code. – peer Jan 28 '21 at 20:26

3 Answers3

1

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
Jalaj Varshney
  • 131
  • 1
  • 9
  • Could you explain what is happening in the for loop after to_print? Just to make sure.. I understand so far that to_print is 5 so in the for loop, we are looking at the range 0 to last row i want. and then prints the last row with space in between? – megarocker241 Jan 28 '21 at 21:16
  • `a` is a 2d array, in which each element represent a row in Pascal's triangle. Now you want the row at index 4. We are looping through 0 to the size of array at index 4. At index 4 the array is : 1, 4, 6, 4, 1. So we are looping from 0 to 4, as the size of this array is 5. We are printing each element. – Jalaj Varshney Jan 28 '21 at 21:26
1

@riam_98, would you like to try this version: It's simplified the logic/flow to take advantage of Pascal key characteristics.

More reading can be found here - https://en.wikipedia.org/wiki/Pascal's_triangle

from typing import List


def getRow(index: int) -> List[int]:

    row = [1]       # firsts row

    if index == 1:  return row

    for i in range(index-1):
        for j in range(i, 0, -1):
            row[j] = row[j] + row[j-1]
        row.append(1)
    return row


print(getRow(2))
print(getRow(3))
print(getRow(4))
print(getRow(5))

Outputs:

[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]   # 5th
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
1

if I wanted to just print 1 row, what would I be changing?

I believe the answers given (and accepted) so far do too much work to obtain the values for an individual row. If we look at Calculating a row or diagonal by itself in the Wikipedia page that @DanielHao recommends, we can generate a simpler solution:

n = int(input("Enter a row number: "))

numbers = [1]

for k in range(1, n):
    numbers.append(numbers[-1] * (n - k) // k)

print(numbers)

We don't need to generate the entire triangle up to the row we desire nor use nested loops to calculate it.

OUTPUT

> python3 test.py
Enter a row number: 5
[1, 4, 6, 4, 1]
> python3 test.py
Enter a row number: 10
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
>

which part of the code is printing the triangle structure? I assume the last for loop?

Yes, but note that it is a fragile, limited solution due to the hardcoding of the number width:

print('{:4}'.format(a[i][j]),end=" ")

For smaller values, the triangle is lopsided, and for values larger than 16, it loses all its symmetry. Here's an example of a Pascal's triangle output that self adjusts Compare it's output to the solution you're asking about.

cdlane
  • 40,441
  • 5
  • 32
  • 81