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/