Python:如何递归模拟范围内的随机游走(无循环)

Eva*_*ter 0 python recursion range random-walk

一个朋友打赌我不能递归地写这个。不幸的是他赢了,但我仍然想知道我将如何去做:

函数为: rw_in_range(start, low, high)

输入是:

start - 一个正整数,表示“梦游者”的起始位置

- 一个正整数,代表“梦游者”将被允许徘徊到的最左边位置

high - 一个正整数,代表“梦游者”将被允许游荡到的最右边位置

低 <= 开始 <= 高

该函数应模拟随机游走,其中“梦游者”在由低和高边界给出的位置范围内徘徊。

梦游者进行随机步骤,其大小由调用我的函数给出:

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: random_step()
    """
    return random.choice([-1, 1])
Run Code Online (Sandbox Code Playgroud)

随机游走应该继续,直到给定的步骤导致“梦游者”到达/超出边界低或高之一。然后,该函数应返回梦游者到达停止位置所需的步数。

例如,第一行的语句print((' ' * start) + 'S')应该是这样的:

>>> rw_in_range(10, 5, 15)
      S
     S
    S
   S
    S
     S
    S
   S
  S
 S
Run Code Online (Sandbox Code Playgroud)

9

我的函数目前看起来像这样:

def rw_in_range(start, low, high):
    print(('' * start) + 'S')
    new_start=start + random_step()
    steps_in_rest= rw_in_range(new_start, low, high)
    if new_start==low or new_start==high: 
        return rw_in_range(new_start, low, high)
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何修复我的代码以使其递归运行此序列?因为它从不返回值。

Jos*_*rez 5

您的函数永远不会返回,因为您在返回时再次调用它。尝试这个:

def rw_in_range(start, low, high):
    print(('' * start) + 'S')
    new_start=start + random_step()
    if new_start<low or new_start>high: 
        return False
    rw_in_range(new_start, low, high)
Run Code Online (Sandbox Code Playgroud)

如果要计算步数,最好的方法是使用列表,如下面的代码所示:

import random

def random_step():
  return random.choice([-1, 1])

def rw_in_range(start, low, high, numberOfSteps):
  if start < low or start > high:
      return False
  print(' '*(low-1)+'|'+' '*(start-low) + 'S'+' '*(high-start)+'|')
  rw_in_range(start + random_step(), low, high, numberOfSteps)
  numberOfSteps[0] += 1
  return True

numberOfSteps = [0]
rw_in_range(10, 5, 15, numberOfSteps)
print numberOfSteps[0]



Output:
rw_in_range(10, 5, 15, numberOfSteps)
    |     S    |
    |    S     |
    |   S      |
    |    S     |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    |   S      |
    |  S       |
    | S        |
    |S         |
    | S        |
    |S         |

>>>print numberOfSteps[0]

22
Run Code Online (Sandbox Code Playgroud)

如果要保留函数的接口,请使用以下代码:

def rw_in_range(start, low, high):
    print((' ' * start) + 'S')
    new_start=start + random_step()
    if new_start<low or new_start>high: 
        return 0
    numberOfSteps = rw_in_range(new_start, low, high)
    return numberOfSteps + 1
Run Code Online (Sandbox Code Playgroud)