Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7536399
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T06:33:49+00:00 2026-05-30T06:33:49+00:00

I’m trying to solve a two-dimensional random walk problem from the book, exploring python.

  • 0

I’m trying to solve a two-dimensional random walk problem from the book, exploring python.
But, I couldn’t figure out how can I solve this problem.I made some research but those were too complicated to understand what is it about. I’m a beginner learner. So, I can’t understand the code by looking it. Please explain me this problem in details.

Anyway, the question is:

The two dimensional variation on the random walk starts in the middle
of a grid, such as an 11 by 11 array. At each step the drunk has four
choices: up, down, left or right. Earlier in the chapter we described
how to create a two-dimensional array of numbers. Using this data
type, write a simulation of the two-dimensional random walk.

Ok, What I know;
I know how to create two dimensional array in python:

times = [0] * 11
for i in range(0,11):
    times[i] = [0] * 11

And I got the idea of “randint” function:

And also I have written the one dimensional variation of this problem recently. But it is a spaghetti code code and and it is very dirty and also I’m not sure if it is right.

My code is here:

'''
Created on Feb 11, 2012

@author: msarialp
'''
from random import randint

def drunken_man():
    steps = 0
    times = [0] * 11
    left_move = 0
    right_move = 0
    i = 0
    while left_move < 5 or right_move < 5:
        value = randint(0,1)
        times[5] = 1
        if value == 1:
            steps += 1
            print("He moved left")
            left_move += 1
            if right_move > 0:
                right_move -= 1
            if left_move == 1:
                times[4] += 1
            elif left_move == 2:
                times[3] += 1
            elif left_move == 3:
                times[2] += 1
            elif left_move == 4:
                times[1] += 1
            #elif left_move == 5:
                #times[0] += 1
        elif value == 0:
            steps += 1
            print("He moved right")
            right_move += 1
            if left_move > 0:
                left_move -= 1
            if right_move == 1:
                times[6] += 1
            elif right_move == 2:
                times[7] += 1
            elif right_move == 3:
                times[8] += 1
            elif right_move == 4:
                times[9] += 1
            #elif right_move == 5:
                #times[10] += 1
        times[i] += 1                
    for i in range(1,10):
        print("He took {steps} steps until he reaches end of the sidewalk.".format(steps = steps),  "He stood on {1} square at {0} times".format(times[i], i) )

def main():
    drunken_man()

    return 0
if __name__ == '__main__':
    main()

EDIT One

After taking some good advices from Dan Gerhardsson.
I’ve decided to edit my question.
So where I am on this question:
I understand how can I follow and examine the steps of my drunken man at two-dimesion.

It was very understandable and clear to use tuple to solve this exercise.

So, after all my code segment is here, Please check and give me any feedbacks.

def two_dimensional_random_walk():
    steps = 0
    times = [0] * 11
    for i in range(0,11):
        times[i] = [0] * 11
    x = 5
    y = 5
    moves = [(1,0), (0,1), (-1,0), (0,-1)]  
    while x<11 and x >= 0 or y < 11 and y >= 0:  
        dx, dy = moves[randint(0,3)]
        x += dx
        y += dy
        if dx == 1 and dy == 0:
            print("He moved right")
        elif dx == 0 and dy == 1:
            print("He moved up")
        elif dx == -1 and dy == 0:
            print("He moved left")
        elif dx == 0 and dy == -1:
            print("He moved down")
        try:
            times[x][y] += 1
            steps += 1
        except IndexError:
            break

And my print function is:

for i in range(0,11):
    for j in range(0,11):
        print("He took {steps} steps until he reaches end of the sidewalk.".format(steps = steps),  "He stood on {1}x{2} square at {0} times".format(times[i][j], i+1,j+1) )   

So all in all I guess with helps by Dan Gerhardsson, I solved the exercise.

But, Why won’t I change my one dimensional solution with those hints.

def drunken_man():
steps = 0
x = 6
times = [0] * 11
moves = [(1), (-1)]

while x < 11 and x >= 0:
    dx = moves[randint(0,1)]
    print(dx, x)
    x += dx
    try:
        times[x] += 1
        steps += 1
    except IndexError:
        break           
for i in range(1,11):
    print("He took {0} steps until he reaches end of the sidewalk.".format(steps),  "He stood on {1} square at {0} times".format(times[i], i) )

EDIT Two(Final touches)

I’m not sure whether it is necessary to edit my post for applying the hints by Dan Gerhardsson. In order to help someone who misses the points like me, I decided to combine everything together.

So here is my function that is combined with hints by Dan Gerhardsson:

def two_dimensional_random_walk():
steps = 0 # Steps counter for understand how many steps that our drunken man take
grid_size = 11 # Grid size variable,
# Creating Two dimensional array by using lists
times = [0] * grid_size 
for i in range(0,grid_size):
    times[i] = [0] * grid_size
# Initial variables to start in the middle of grid
x = 5
y = 5
# Tuples to get directions and decide where to go
moves = [(1,0, "right"), (0,1, "up"), (-1,0, "left"), (0,-1, "down")] 
# My loop for evaluate the steps
while True:  
    dx, dy, position = moves[randint(0,3)] # By using randint I could make decision randomly
    x += dx
    y += dy
    print("He moved", position)
    try:
        times[x][y] += 1 # And here is, how many times have he stood on each square
        steps += 1
    except IndexError: # The exit of loop
        break
# My print function which answers these questions (How long will it be until he reaeches the end of the sidewalk, and how many times will he have stood on each square)
for i in range(0,11):
    for j in range(0,11):
        print("He took {steps} steps until he reaches end of the sidewalk.".format(steps = steps),  "He stood on {1}x{2} square at {0} times".format(times[i][j], i+1,j+1) )

Thanks for your big helps Dan Gerhardsson.
I guess finally I’ve got the solution.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T06:33:50+00:00Added an answer on May 30, 2026 at 6:33 am

    I can at least give you a few hints. So you have four possible moves. Each move can be represented by a tuple which is the displacement in the x and y directions:

    moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    

    To set the start position in the center:

    grid_size = 11
    x = grid_size // 2
    y = grid_size // 2
    

    Store the position of the drunken man and update it in each step of the simulation. Something like this:

    # Displacement:
    dx, dy = random.choice(moves)
    
    # Update position:
    x += dx
    y += dy
    

    This might not be beginner level code, but instead of checking the boundaries with an if-statement, you can try to update the count, and handle the exception, which is raised if the position is outside the grid:

    try:
        # Update counter.
        times[x][y] += 1
    except IndexError:
        # Exit the simulation loop.
        break
    

    Hope this helps.

    EDIT – Comments on the second version:

    Since you want to print the direction in each step, you can add that to the tuple:

    moves = [(0, 1, 'up'), (1, 0, 'right'), (0, -1, 'down'), (-1, 0, 'left')]
    

    Then you can replace the if-statement where you print the direction:

    dx, dy, direction = random.choice(moves)
    print('He moved', direction)
    

    When you use try-except as in your current solution, you don’t need to check the boundaries in the while-statement. You can just do:

    while True:
        ...
    

    since the break in the exception handler will exit the loop.

    My final piece of advice is to replace some of the number literals with variables. The grid size e.g. appears in more than one place. You should create a variable and refer to it in the rest of the code:

    grid_size = 11
    times = [0] * grid_size
        for i in range(grid_size):
            times[i] = [0] * grid_size
    

    Using a variable instead of number literals means that you just have to make a change at one place if you want to run the code with a different grid size.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am currently running into a problem where an element is coming back from
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.