【问题标题】:How can I successfully complete the random walk problem?如何成功完成随机游走问题?
【发布时间】:2019-11-17 05:56:51
【问题描述】:

我正在为一个模拟 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)

【问题讨论】:

  • 有什么问题?在我看来,您只是不调用 randint 方法(即使有良好的界限),而只是分配它
  • 你return之后的print语句永远不会被执行,你需要把print语句放在return语句之前。
  • 你应该更好地重新表述你的问题,因为它不清楚

标签: python random-walk


【解决方案1】:

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

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    相关资源
    最近更新 更多