Skip to content

Commit 73a2272

Browse files
authored
Create pascals_triangle.py
1 parent 82aa909 commit 73a2272

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

maths/pascals_triangle.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""/**
2+
* Pascal's Triangle is an array of binomial coefficients. It can be used for unwrapping terms like
3+
* (a + b)^5.
4+
* To construct Pascal's Triangle you add the numbers above the child entry together. Here are the first five rows:
5+
* 1
6+
* 1 1
7+
* 1 2 1
8+
* 1 3 3 1
9+
* 1 4 6 4 1
10+
*
11+
* Time Complexity: quadratic (O(n^2)).
12+
* @see https://en.wikipedia.org/wiki/Pascal's_triangle
13+
*/ """
14+
15+
# Importing the numpy library as np for numerical operations
16+
import numpy as np
17+
18+
def pascal(n: int):
19+
"""
20+
Generate Pascal's triangle up to the n-th row.
21+
Parameters:
22+
n (int): The number of rows in Pascal's triangle to generate.
23+
Returns:
24+
np.ndarray: A 2D numpy array containing the first n rows of Pascal's triangle.
25+
"""
26+
# Initialize a 2D numpy array with zeros, with shape (n,n) and integer type
27+
pascal_array = np.zeros((n, n), dtype=np.int64)
28+
# Set the first column of all rows to 1 (the edge values of Pascal's triangle)
29+
pascal_array[:, 0] = 1
30+
31+
# Fill the pascal_array with the correct values for Pascal's triangle
32+
for i in range(1, n):
33+
# Each element except the edges is the sum of the two directly above it
34+
# pascal_array[i, 1:n] = pascal_array[i-1, 1:n] + pascal_array[i-1, 0:n-1]
35+
pascal_array[i,1:i+1] = pascal_array[i-1,1:i+1] + pascal_array[i-1,0:i]
36+
37+
return pascal_array
38+
39+
def show_pascal(pascal_array):
40+
"""
41+
Print Pascal's triangle in a formatted manner.
42+
Parameters:
43+
pascal_array (np.ndarray): A 2D numpy array containing Pascal's triangle.
44+
"""
45+
# Get the number of rows and columns (should be equal)
46+
n, m = pascal_array.shape[:2]
47+
# Ensure the array is square (n == m), as required for Pascal's triangle
48+
assert n == m
49+
50+
# Loop through each row and print the values up to the current row index
51+
for i in range(n):
52+
for j in range(i + 1):
53+
print(pascal_array[i, j], end=" ")
54+
print()
55+
56+
# Main execution block
57+
if __name__ == '__main__':
58+
# Display Pascal's triangle for 10 rows
59+
show_pascal(pascal(10))

0 commit comments

Comments
 (0)