Worksheet: 2D lists

Worksheet

CS 151 Worksheet - 2D lists

Solutions for Question 3

def pascalsTriangle( n:int ) -> list:

"""Compute the first n rows of Pascal's triangle and return the resulting 2D list."""

# first, create the triangle with cells holding a default -1

triangle:list = []


# create a list for each row

for r in range( n ):

# the list should have r+1 entries

row:list = [-1]*(r+1)


# add it to the triangle

triangle.append(row)


# initialize the first cell to have value 1

triangle[0][0] = 1


# then, for every row beyond the first row

for r in range( 1, n ):

# the first entry/column is a 1 by definition

triangle[r][0] = 1


# for each subsequent column up to (but not including the final column)

for c in range( 1, r ):

# the next value is the sum of the value above

# with the value above and to the left


triangle[r][c] = triangle[r-1][c] + triangle[r-1][c-1]


# fill in the final 1 to complete the row

triangle[r][r] = 1


# return the computed triangle

return triangle

More practice

Write a function to compute the first n rows of the Bell triangle.

Solutions

def bellTriangle( n:int ) -> list:

"""Compute the first n rows of the Bell triangle and return the resulting 2D list."""

# first, create the triangle with cells holding a default -1

triangle:list = []


# create a list for each row

for r in range( n ):

# the list should have r+1 entries

row:list = [-1]*(r+1)


# add it to the triangle

triangle.append(row)


# initialize the first cell to have value 1

triangle[0][0] = 1


# then, for every row beyond the first row

for r in range( 1, n ):

# the first entry/column is the last entry of the previous

triangle[r][0] = triangle[r-1][r-1]


# for each subsequent column

for c in range( 1, r+1 ):

# the next value is the sum of the value to the left

# with the value above and to the left


triangle[r][c] = triangle[r][c-1] + triangle[r-1][c-1]


# return the computed triangle

return triangle