Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pascals triangle

                 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
Comment

Pascal triangle

"""
This implementation demonstrates how to
generate the elements of Pascal's
triangle (https://en.wikipedia.org/wiki/Pascal%27s_triangle).

Let n be the number of rows to create.

Time complexity: O(n^2)
Space complexity: O(1)
"""


def generate_triangle(num_rows):
    triangle = []
    for row_idx in range(num_rows):
        current_row = [None] * (row_idx+1)
        # first and last elements of current row are always 1
        current_row[0], current_row[-1] = 1, 1
        for col_idx in range(1, row_idx):
            above_to_left_elt = triangle[row_idx - 1][col_idx-1]
            above_to_right_elt = triangle[row_idx - 1][col_idx]
            current_row[col_idx] = above_to_left_elt + above_to_right_elt
        triangle.append(current_row)
    return triangle


# Below prints: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
print(generate_triangle(5))
Comment

PREVIOUS NEXT
Code Example
Python :: class variable in python 
Python :: numpy concatenate arrays 
Python :: how to remove whitespace from string in python 
Python :: insert value in string python 
Python :: gui def python 
Python :: scale values in 0 100 python 
Python :: loading bar python 
Python :: 151 - Power Crisis 
Python :: del df.loc 
Python :: python emoji convert 
Python :: pdfs in django 
Python :: ros teleop 
Python :: convert png rgba to rgb pyhton 
Python :: compiling python code 
Python :: How split() works in Python? 
Python :: aiohttp specify app IP 
Python :: clear terminal in python 
Python :: inverse of a matrix with determinant 0 python linalg 
Python :: custom dataset pytorch 
Python :: rank function in pandas 
Python :: read csv pandas nrow 
Python :: python set terminal size 
Python :: python get ids from array of objects 
Python :: how to check python version in script 
Python :: onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] 
Python :: change creation date filesystem py 
Python :: if in one line python 
Python :: capitalise texts 
Python :: write a python program to find the second largest number in a list 
Python :: Common Python String Methods 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =