python - 如何递归模拟随机游走?无循环(Python)

标签 python recursion simulation 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])

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

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

  • start,一个整数,代表梦游者的起始位置
  • numsteps,一个正整数,表示从起始位置开始的随机步数

它应该模拟由 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

我目前拥有的:

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

是否可以用递归来写?

最佳答案

您的代码中有几个错误。试试这个:

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

它应该可以工作。

关于python - 如何递归模拟随机游走?无循环(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087331/

相关文章:

python - "\n"会立即转换为 python 中的换行符吗?

python - 用于多索引的 Pandas mean()

python - 在 pygame 物理模拟中添加 wxPython GUI 元素

azure - 用于模拟的 Windows Azure

python - 如何在现有列表后添加列表但不扩展它?

python - 根据概率将变量设置为不同的值

algorithm - 通过 DP 最大化给定股票数据的利润

java - Java阶乘程序中的递归

haskell - 使用 Maybe monad 终止相互递归函数

algorithm - 在 1-DOF 质量 Spring 系统中实现半隐式后向欧拉