Random Walk in Python Code

Reply Tue 23 Feb, 2016 07:53 am
I need to modify this code to show a random walk on a 10*10 matrix. The walker will move by one element at a time labeled A through Z by moving up,down,left or right. The walker can never go outside of the matrix either.

Please help, I have never looked at programming before and I am completely lost.

#You need to debug and modify the program so that it is able to do random walking
import random

N = 10
FILLER = '.'

#create a list to represent a row
#The row at first is filled with FILLER '.'
line = []
for i in range(N):

#create a matrix
#The matrix is the maze to walk
for i in range(N):
line = line[:]

#always starts at the left top corner of the matrix
#fill the matrix cell at the left top corner 'A'
x = 0
y = 0
letter = 'A'
a[x][y] = letter

#a sequence of random walk steps
#The below loop will settle the next letter
letter = chr(ord(letter) + 1)
#Where to go from the current sell: right, left, down, or up?
#We need a bit of randomness
direction = random.randrange(0, 4);
#keep track of the directions tried
moves_tried = 0 #trials to put a letter

#The following loop broken either due to
#running out of letters or
#having tried four directions
while (moves_tried < 4 and letter <= 'Z'):
#turn is random but its value is always between 0 and 3
turn = (direction + moves_tried) % 4
if (turn == 0): #right
new_x = x
new_y = y + 1
elif (turn == 1): #left
new_x = x
new_y = y - 1
elif (turn == 2): #down
new_x = x + 1
new_y = y
else: #up
new_x = x - 1
new_y = y
#check the new position (new_x, new_y) to see if the letter can be settled
if (0 <= new_x and new_x < N and 0 <= new_y and new_y < N and a[new_x][new_y] == FILLER):
#label the target element and prepare the next iteration

moves_tried = moves_tried + 1
for i in range(N):
#use (' '.join(a)) to get a string
#print the ith row a of the matrix
  • Topic Stats
  • Top Replies
  • Link to this Topic
Type: Question • Score: 0 • Views: 1,546 • Replies: 0
No top replies


Related Topics

HVAC lines - Question by alevythiebaut
css - Question by keerthi60
Hacked on Facebook - Question by Hopea
need help with this code - Question by Philoue
Hide/Unhide Columns - Question by N Prakash
Help with a Code - Question by Joshua5
  1. Forums
  2. » Random Walk in Python Code
Copyright © 2020 MadLab, LLC :: Terms of Service :: Privacy Policy :: Page generated in 0.03 seconds on 07/11/2020 at 11:27:47