Search code examples
pythonrecursionsimulationrandom-walk

How to Recursively Simulate a Random Walk? No Loops (Python)


Python Question

I have a function for 1 random step:

def random_step(): 
    """ chooses a random step (-1 or 1) and returns it.
        inputs: none! However, make sure to use parens when calling it.
            For example: ramdom_step()
    """
    return random.choice([-1, 1])

And I need to call it in this function I am writing:

rw_outcome( start, numsteps ), that takes two inputs:

  • start, an integer that represents the starting position of the sleepwalker
  • numsteps, a positive int that represents the # of random steps to take from the starting position

It should simulate a random walk consisting of numsteps random steps whose sizes are determined using calls to random_step(), but I keep returning the same starting position.

An example of what it should return with print('start is', start):

>>> rw_outcome(40, 4)
start is 40
start is 41
start is 42
start is 41
start is 42
42

What I have so far:

def rw_outcome(start, numsteps):
    print('start is', start)
    if start + (numsteps*random_step()) == 0:
        return 0
    else:
        return rw_outcome(start,numsteps+1)

Is it possible to write with recursion?


Solution

  • There was a couple of errors in your code. Try this:

    def rw_outcome(start, numsteps):
    print('start is', start)
    if numsteps == 0:
        return 0
    else:
        return rw_outcome(start+random_step(),numsteps-1)
    

    It should work.