I have written a program that takes a number n
and prints Pascal's triangle having n
number of rows.
Here is my code -
n = int(input("Enter number of rows: "))
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('{0:5}'.format(a[i][j]), end = " ", sep = " ")
print()
Here are some example outputs -
Enter number of rows: 3
1
1 1
1 2 1
Enter number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter number of rows: 10
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
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Therefore, I would like to know whether I could make this program shorter and more efficient.
Any help would be highly appreciated.
append
as much as possible. It's usually easy to do so. \$\endgroup\$