Question
def diagonal_grid(height, width): creates and returns a height x width grid in which the cells on the diagonal are set to 1, and all
def diagonal_grid(height, width): """ creates and returns a height x width grid in which the cells on the diagonal are set to 1, and all other cells are 0. inputs: height and width are non-negative integers """ grid = create_grid(height, width) # initially all 0s for r in range(height): for c in range(width): if r == c: grid[r][c] = 1
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):
>>> grid = random_grid(10, 10) >>> print_grid(grid) 0000000000 0100000110 0001111100 0101011110 0000111000 0010101010 0010111010 0011010110 0110001000 0000000000
Our starter code imports Pythons 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.
return grid
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 diagonali.e., the cells whose row and column indices are the sameto 1.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started