For today’s challenge, we need to write a program that prints out the Pascal Triangle.
Pascal Triangle is named after Blaise Pascal, a famous French Mathematician and Philosopher. An example is shown below:
To build the triangle, you start with 1 at the top row, followed by 1, 2, 1 in the second row.
From the third row onwards, you start with 1, then add the two numbers in the previous row to get the next value.
For instance, to get the second number in row 3, you add the first and second number in row 2 to get 3 (i.e. 1 + 2 = 3)
To get the third number in row 3, you add the second and third number in row 2. This gives us 3 as well (2 + 1 = 3).
Finally, you end the row with the number 1 again.
Clear? Let’s look at one more example.
Suppose you want to get the fourth number in row 6. To do that, you add the third and fourth number in row 5. This gives us 20 (10 + 10 = 20).
Our challenge today is to write a program to print out the Pascal Triangle. The program will first prompt users for the number of rows they want. It’ll then print the triangle as requested.
Here’s a video showing how the program works.
As this project is slightly longer than usual, we’ll use a different format today.
Today, we’ll be doing it as a follow-along tutorial. If you want to see the final code, you can click here.
If you want to code this program together, just read on.
The Pascal Triangle in our program is displayed using a table consisting of rows and columns.
An example (showing 5 rows of the triangle) is shown in the diagram below:
For each row, between the first and the last number, alternate columns are blank.
For instance, for row 4, the first and last numbers occur at columns 2 and 10 respectively. Between these two columns, alternate columns are blank. In other words, columns 3, 5, 7, 9 are blank.
Similarly, for row 5, the first and last numbers occur at columns 1 and 11. Hence, columns 2, 4, 6, 8 and 10 are blank.
Clear about how this table works? Good.
In order to display this table, we need to do some calculations.
Specifically, we need to figure out the number of blank columns we have before the first number.
The table below lists this information for each row (for a triangle with 5 rows).
We can see that the first row is special. The number of blank columns in the first row (before the first number) is equal to the number of rows in the triangle.
From the second row onwards, if we let n
be the number of rows in the triangle (n = 5
in our example) and r
be the current row, we can see that the number of blank columns = n – r
.
With that, we are ready to start coding our program.
We need to code three functions – printSpaces()
, printRow()
and getRow()
.
Let’s work on the first function – printSpaces()
. This function prints the empty columns before the first number for each row and has two parameters – numOfRows
and currentRow
.
numOfRows
represents the number of rows the Pascal Triangle has (denoted by n
in the formulas above).
currentRow
represents the current row that we are printing (denoted by r
in the formulas above).
Try declaring this function yourself.
Within the function, we first declare a variable called numberOfBlankColumns
and initialize it to zero. Try doing this yourself.
Next, we’ll use an if-else
statement to update the value of numberOfBlankColumns
using the formulas above.
Within the if
block, we check if currentRow
equals 1. If it is, we assign numOfRows
to numberOfBlankColumns
.
If it is not, we assign numOfRows – currentRow
to numberOfBlankColumns
.
Try writing this if-else
statement yourself.
Once that is done, we need to print the blank columns. To do that, we’ll use a for
loop.
Suppose we want to use a single space to represent a blank column and we want to print 5 blank columns, we can do it as follows:
for i in range(5):
print(' ', end = '')
When we add end = ''
(two single quotes) to the print()
function, the function does not move the cursor to the next line after printing each space. Hence, we’ll get 5 spaces as a single row of output.
In our case, we want to use 3 spaces to represent a blank column. Try modifying the for
loop above to print the blank columns for our Pascal Triangle.
Clear?
Once that is done, the printSpaces()
function is complete.
The next function is the printRow()
function. This function prints the numbers in the Pascal Triangle and has one parameter row
.
row
is a list that stores the numbers in each row of the triangle. For instance, for the third row, row = [1, 3, 3, 1]
Within the function, we first declare a variable called space
and assign the string ' '
to it. This string is made up of three spaces.
Next, we use the for
loop below to loop through the elements in row
and print them one by one.
for i in range(len(row)):
#print the elements in row
Recall that we use 3 spaces to represent one blank column in our Pascal Triangle?
We need to use the same length when printing our numbers. To achieve this, we’ll use a built-in function in Python (the center()
function) to help us set the length of our number columns to 3 and align the numbers to the center of the column.
This built-in function takes in two arguments – the length of the resulting string and the character used to pad the string to the desired length. The second argument is optional. If it is omitted, a space will be used.
For instance, suppose we write
'A'.center(5, '-')
we’ll get
--A--
as the output, where the total length of the resulting string is 5, with ‘A’ in the center and ‘-‘ used to pad the rest of the string.
In our printRow()
function (within the for
loop), we need to first cast row[i]
into a string. We then use this string to call the center()
function, passing in 3 as the argument. Finally, we pass the resulting string to the print()
function to print out the number, padded to a length of 3.
After printing the number, we need to print an empty column (represented by the space
variable).
Try writing this for
loop yourself. Remember to add end = ''
to the print()
function to prevent the cursor from moving to the next line after each number and blank column.
Once that is done, we add the line
print()
outside the for
loop to move the cursor to the next line after printing all the elements in row
.
Clear? Once you have finished coding this function, you can check if your function performs correctly by executing the following statement:
printRow([1, 2, 1])
You should get
1 2 1
as the output (where there’s one space before the first number, 4 spaces after the last, and five spaces between numbers).
Got it? If your output is different, you can refer to the solution here and compare your code.
If it is the same, we can move on to the getRow()
function. This function is used to calculate the numbers in each row of the Pascal Triangle. The function has one parameter – previousRow
.
previousRow
is a list that contains numbers from the previous row.
Try declaring the function yourself. Within the function, we first initialize a list called currentRow
as follows:
currentRow = [1]
Next, we’ll use a for
loop to loop through the elements in previousRow
. This for
loop adds each element in previousRow
to the element after it and appends the sum to currentRow
.
For instance, suppose previousRow = [1, 3, 3, 1]
.
The for
loop should do the following:
currentRow.append(1+3)
currentRow.append(3+3)
currentRow.append(3+1)
This results in currentRow
becoming [1, 4, 6, 4]
.
Try coding this for
loop yourself.
Once that is complete, we need to append the number 1 to currentRow
so that currentRow
becomes [1, 4, 6, 4, 1]
.
With that, the function is almost complete. We simply need to return currentRow
.
Clear? Try coding the function yourself.
Once you have finished coding the function, we are ready to print our Pascal Triangle.
First, we’ll prompt the user for the number of rows they want to print and assign the input to a variable called rows
.
Next, we’ll print the first and second rows. To do that, we need to use the printSpaces()
and printRow()
functions. The lines below show how to print the first row:
printSpaces(rows, 1)
printRow([1])
Add two more lines to print the second row. (Hint: The second row of the Pascal Triangle consists of the numbers 1, 2, 1)
Next, we’ll assign the list [1, 2, 1]
to a variable called previousRow
. We’ll then use the following for
loop to print the remaining rows:
for i in range(3, rows+1):
#print remaining rows
Within the for
loop, we need to do the following:
- Use the
printSpaces()
function to print the spaces before the first number. - Use the
getRow()
function (passing inpreviousRow
as the argument) to get the numbers for the current row. Assign the result tocurrentRow
. - Use the
printRow()
function to print the numbers incurrentRow
. - Assign
currentRow
topreviousRow
.
Try writing this for
loop yourself. Once that is done, the program is complete. Try running it to see if it produces the desired output.
The complete code is given below:
def printSpaces(numOfRows, currentRow):
numberOfBlankColumns = 0
if (currentRow == 1):
numberOfBlankColumns = numOfRows
else:
numberOfBlankColumns = numOfRows - currentRow
for i in range(3*numberOfBlankColumns):
print(' ', end = '')
def printRow(row):
space = ' '
for i in range(len(row)):
print(str(row[i]).center(3), end = '')
print(space, end = '')
print()
def getRow(previousRow):
currentRow = [1]
for i in range(0, len(previousRow)-1):
currentRow.append(previousRow[i] + previousRow[i+1])
currentRow.append(1)
return currentRow
#Prompt users for number of rows
rows = int(input('Number of rows: '))
#Print first and second row
printSpaces(rows, 1)
printRow([1])
printSpaces(rows, 2)
printRow([1, 2, 1])
#Print third row onwards
previousRow = [1, 2, 1]
for i in range(3, rows+1):
printSpaces(rows, i)
currentRow = getRow(previousRow)
printRow(currentRow)
previousRow = currentRow