Search code examples
pythonrandom-walk

Python: Drunkard's walk


I have to write a code to calculate route and length of a drunkard's walk.

Excersise: A drunkard begins walking aimlessly, starting at a lamp post. At each time step he takes one step at random, either north, east, south, or west. How far will the drunkard be from the lamp post after N steps? In order to emulate drunkard's steps we can encode each direction with the number so that when the random variable is equal to 0 the drunkard moves north, if random variable is equal to 1 the drunkard moves east and so on.

Write a program that takes an integer argument N and simulates the motion of a random walker for N steps. After each step, print the location of the random walker, treating the lamp post as the origin (0, 0). Also, print the final squared distance from the origin.

So far I've come up with:

import random
x = 0
y = 0
def randomWalk(N):
    for i in range (1, (N)):
        a = random.randint
        if a == 0:
            x = x+0
            y = y+1
            return (x, y)
            print (x, y)
        if a == 1:
            x = x+1
            y = y+0
            return (x, y)
            print (x, y)
        if a == 3:
            x = x+0
            y = y-1
            return (x, y)
            print (x, y)
        if a == 3:
            x = x-1
            y = y+0
            return (x, y)
            print (x, y)
print(randomWalk(input()))

But I get None as output, when I test this code.

I would be thankful for any help with this excersise.


Solution

  • It's a good start.

    The main problem is that you are failing to call randint:

        a = random.randint
    

    This just turns a into an alias for random.randint. Instead, it should be

        a = random.randint(0, 3)
    

    Also, you repeat if a == 3: twice.

    Also, setting x and y to zero should be done inside the function, not outside.

    Finally, your loop (which, by the way, is one iteration too short) doesn't really function as a loop, since you always return during the first iteration.

    P.S. Here is a little parting puzzle for you. Figure out how the following works:

    dx, dy = random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
    x += dx
    y += dy