如何成功完成随机游走问题?

时间:2019-11-16 21:33:10

标签: python random-walk

我一直在寻找帮助编写此程序的代码,该程序模拟25个步骤的随机游走。

(人)可以向东或向西行走。

程序必须计算以下内容并将其输出到屏幕:

25个步骤结束时距起点的平均距离。 在25个步骤中,随机游走返回起点的平均次数。

它还模拟了一个随机的增量步长:1步,然后2步,然后3步,然后4步,...,最多50步。

注意:1 =东部,2 =西部

这是我到目前为止的内容,任何建议将不胜感激。

import random
x = 0
y = 0
def randomWalk(N):
  for i in range (1, (N)):
    a = random.randint
    if a == 1:
        x = x+1
        y = y+0
        return (x, y)
        print (x, y)
    if a == 2:
        x = x+0
        y = y-1
        return (x, y)
        print (x, y)

1 个答案:

答案 0 :(得分:0)

我创建了一个可以学习的算法。在代码中,我添加了注释,描述了所做的更改以及代码不起作用的区域。

import random

def randomWalk(N):
    # It's best to initialize variables inside a function
    # Here, I assumed x is the position relative to the starting point
    # while y is the number of times the person crossed the starting point (0)
    x = 0
    y = 0
    # You would want a range from 0 to N
    # This is because you want N steps
    for i in range(N):
        # Make sure you are calling random.randint by using parentheses
        # The function takes in two arguments, which specify the bounds, inclusive
        a = random.randint(1, 2)
        if a == 1:
            # Instead of doing x = x + 1 you can do x += 1
            x += 1
        else:
            # Same thing here
            x -= 1
        # This detects whether the person is on the starting point
        # and adds 1 to y if they are
        if x == 0:
            y += 1
    # You want to return x and y at the end of the for loop
    # You were previously returning it after 1 iteration
    return x, y

# Testing randomWalk with 15 steps
print(randomWalk(15))