Evan Porter
Evan Porter

Reputation: 15

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:

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?

Upvotes: 1

Views: 1313

Answers (2)

Mistsz1
Mistsz1

Reputation: 181

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.

Upvotes: 5

Dennis Sakva
Dennis Sakva

Reputation: 1467

Something like this?

def random_step(nsteps=1):
    if nsteps>0:
        return random_step(nsteps-1)+random.choice([-1, 1])
    else:
        return 0

def rw_outcome(start, numsteps):
    return start+random_step(numsteps)

Upvotes: 0

Related Questions