Pascal triangle using list comprehension

77 Views Asked by At

As the title says, I have a problem using list comprehension for creating the Pascal Triangle.

n = int(input())
a = []
a = [[1 if j > 0 and j < n-1 else a[i-1][j] + a[i-1][j-1] for j in range(i)] for i in range(n)]
print(*a, sep = '\n')

I get the following error: (https://i.stack.imgur.com/dd6w5.png)

I don't understand where the index gets out of range and how I can fix it. Thank you.

2

There are 2 best solutions below

0
Andrej Kesely On

To compute pascal triangle using list comprehension, you can use math.factorial:

from math import factorial as fct

rows = [[int(fct(n) / (fct(k) * fct(n - k))) for k in range(n + 1)] for n in range(5)]
print(*rows, sep="\n")

Prints:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
0
trincot On

There are a few issues in your attempt:

  • You used the if..else operator in the opposite way: you'll want to produce 1 when the if condition is false, not when it is true.

  • j < n-1 is not the right limit condition. It should be j < i, and j should be in the range range(i+1).

  • Your comprehension never updates the a list, so the incremental update idea is not working. a remains empty until the whole comprehension has finished, while you'll want a to be incrementally updated at each increment of i. You can use a := syntax to track the last row, while the list comprehension will use those rows to populate the triangle.

Here is your code updated with those remarks taken into account:

n = int(input())
a = []
a = [
    a := [
        a[j] + a[j-1] if 0 < j < i else 1
        for j in range(i+1)
    ]
    for i in range(n)
]

print(*a, sep = '\n')

Now it will work.