如何递归模拟随机游走?没有循环(Python)

Eva*_*ter 1 python simulation recursion random-walk

Python问题

我有一个随机步骤的功能:

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])
Run Code Online (Sandbox Code Playgroud)

我需要在我写的这个函数中调用它:

rw_outcome( start, numsteps ),需要两个输入:

  • start,一个表示梦游者起始位置的整数
  • numsteps,一个正int,表示从起始位置获取的随机步骤数

它应该模拟随机游走,其中包含numsteps随机步骤,其大小是使用调用来确定的random_step(),但我会继续返回相同的起始位置.

它应该与print返回的一个例子('start is',start):

>>> rw_outcome(40, 4)
start is 40
start is 41
start is 42
start is 41
start is 42
42
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的:

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

是否可以用递归写?

Mis*_*sz1 5

您的代码中存在一些错误.试试这个:

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

它应该工作.