A recent task at ALX Software Engineering Program was to develop a function (using Python) that generates a Pascal's triangle of a given number of rows (n) and returns it as a list of lists of integers.
This is a tutorial on how I approached and solved the task.
Why does Pascal have a Triangle?
Paschal has a triangle because he is named after a French mathematician Blaise Pascal. Pascal's triangle is an array of numbers arranged in a triangular pattern. The first and last number of each row is always 1, and each number inside the triangle is the sum of the two numbers diagonally above it in the previous row.
NOTE - My function employs the mathematical formula for combinations to generate the Pascal's triangle. In case you're not familiar with the formula, you may want to refresh your knowledge before we dive in.
Step 1 - List of Lists
Firstly, we create a pascal_triangle(n)
function that generates a pascal's triangle of size n
using the mathematical formula for combination. The function starts by defining an empty list called matrix
, which will later be used to store the rows of the triangle.
The function then enters a for loop that will iterate n
times. Each iteration of the loop corresponds to a row in the triangle. Within this for loop, the function defines another list called rows
, which will be used to store the elements of the current row.
def pascal_triangle(n):
""" Representing the pascal's triangle of n. """
# Define matrix
matrix = []
# n stands for number of rows so we will iterate n times
for x in range(n):
# Define rows
rows = []
for y in range(x + 1):
# Find the combination of x and y
result = comb(x, y)
# Append result to inner list
rows.append(result)
# Append inner list to matrix
matrix.append(rows)
# Return list of list
return matrix
The function then enters another for loop that will iterate x+1 times
, where x
is the current iteration of the outer loop. Within this inner loop, the function calculates the combination of x
and y
using the comb(a, b)
function, where a
is x
and b
is y
. The function then appends the result of the combination to the rows
list.
After the inner loop completes, the function appends the rows
list to the matrix
list. This completes one row of the triangle. The outer loop then continues to the next iteration, generating the next row of the triangle.
Once the outer loop completes, the function returns the matrix
list, which contains all of the rows of the triangle.
Step 2 - Combinations
We then create a comb(a, b)
function to calculate the number of ways to choose b
items from a set of a
items. The function uses the mathematical formula for combination, which is:
comb(a, b) = a! / (b! * (a-b)!)
Where a!
is the factorial of a, b!
is the factorial of b, and (a-b)!
is the factorial of a-b.
The comb(a, b)
function first calls the factorial(n)
function to calculate the factorials of a, b and a-b and then returns the result of the combination calculation.
Step 3 - Factorial
The factorial(n)
function is a simple recursive function that calculates the factorial of a given non-negative integer n
.
The exclamation mark (!) denotes the factorial operation, which is the product of all positive integers up to and including the number.
For example, 5! = 5 x 4 x 3 x 2 x 1 = 120.
We start with a base case that checks if the input n
is equal to 0, in which case it immediately returns 1. This is because the factorial of 0 is defined as 1.
If n
is greater than 0, the function uses recursion to call itself with the input n-1
and multiplies the result by n
.
Step 4 - Print Triangle
Finally we are ready to print our rows and represent them in a triangular format.
We define a variable my_triangle
that stores the result of the pascal_triangle(5)
function which is represented as a list of lists, where each sublist is a row of the triangle, and each element in a row is an element of the triangle.
Next, the code enters a for loop that iterates through the my_triangle
list, using the enumerate()
function.
my_triangle = pascal_triangle(5)
# Iterate through our matrix
for i, row in enumerate(my_triangle):
# Store spaces as strings
spaces = " " * (len(my_triangle) - i - 1)
# Store row elements as strings and seperate with space
rows = " ".join(str(x) for x in row)
# Print row element
print(f"{spaces}{rows}")
Within our for loop, we create a variable spaces
that stores a string of spaces.
Next, we create a variable rows
that stores a string representation of the current row of the triangle, with each element separated by a space. The str(x)
function is used to convert each element in the row to a string, and the built-in join()
is used to concatenate the strings with a space in between.
We then call print()
to print our triangle and it looks like this.
pascal_triangle$ ./pascal.py
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Limitations
The pascal_triangle(n)
function does not currently check if the input n
is less than or equal to 0, so its behavior in such cases is unpredictable.
Links
- You can find the rest of the code for Pascal Triangle on Github
If this article was helpful in your understanding of pascal's triangle, please leave a comment in the section below. Your feedback is appreciated. Also, do follow me for more informative articles like this one.
Top comments (0)