1

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)

可以用递归写吗?

4

2 回答 2

5

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

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

它应该工作。

于 2014-09-28T17:15:42.237 回答
0

像这样的东西?

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)
于 2014-09-28T17:12:32.850 回答