Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write this python program 5. Random walk. You may know that the streets and aven

ID: 3602044 • Letter: W

Question


write this python program

5. Random walk. You may know that the streets and avenues of Manhattan form a grid. A random walk through the grid (i.e., Manhattan) is a walk in which a random direction (N, E, S, or W) is chosen with equal probability at every intersection. For example, a random walk on a 5 × 11 grid starting at (5, 2) could visit grid points (6, 2), (7, 2), (8, 2), (9, 2), (10, 2), back to (9, 2) and then back to (10, 2) before leaving the grid. Write function manhattan ) that takes the number of rows and columns in the grid, simulates a random walk starting in the center of the grid, and computes the number of times each intersection has been visited by the random walk. Your function should print the table line by line once the random walk moves outside the grid. As an example, the call manhattan(5, 11) could produce the following output: Co, 0, o, o, 0, 0, 0, o, 0, 0, 0] [o, 0, 0, 0, 0, 0, 0, 0, o, 0, 0] to, 0, 0, 0, 0, 0, 0, 0, 0, o, 0] to, 0, 0, o, o, o, 0, 0, 0, 0, 0]

Explanation / Answer

import math
def manhattan(row, column):
a = [[0] * column for i in range(row)]
x = math.ceil(row/2)-1
y = math.ceil(column/2)-1
for i in range(y, column):
a[x][i] = a[x][i] + 1
a[x][column-2] = a[x][column-2] + 1
a[x][column-1] = a[x][column-1] + 1
for row in a:
print(' '.join([str(elem) for elem in row]))

manhattan(5, 11)

As per the sample output, I am staring from the center of the grid and travelling to right.

Output:

0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 2 2
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0