Based on the example of diagonal_grid, write a function Write a function random_
ID: 3740187 • Letter: B
Question
Based on the example of diagonal_grid, write a function Write a function random_grid(height, width) that creates and returns a 2-D list of height rows and width columns in which the inner cells are randomly assigned either 0 or 1, but the cells on the outer border are all 0.
For example (although the actual values of the inner cells will vary):
Our starter code imports Python’s random module, and you should use the random.choicefunction to randomly choose the value of each cell in the grid. Use the call random.choice([0, 1]), which will return either a 0 or a 1.
Notice that the function first uses create_grid to create a 2-D grid of all zeros. It then uses nested loops to set all of the cells on the diagonal–i.e., the cells whose row and column indices are the same–to 1.
Explanation / Answer
from random import randint def create_grid(height, width): grid = [] for i in range(height): lst = [] for j in range(width): lst.append(0) grid.append(lst) return grid def random_grid(height, width): grid = create_grid(height, width) # initially all 0s for r in range(height): for c in range(width): if r == 0 or r == height-1 or c == 0 or c == width-1: grid[r][c] = 0 else: grid[r][c] = randint(0, 1) return grid print(random_grid(10, 10))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.