2

我必须编写一个代码来计算醉汉步行的路线和长度。

练习:一个酒鬼开始漫无目的地走,从灯柱开始。在每个时间步,他随机走一步,无论是向北、向东、向南还是向西。N步后酒鬼离灯柱有多远?为了模仿醉汉的脚步,我们可以用数字对每个方向进行编码,这样当随机变量等于 0 时醉汉向北移动,如果随机变量等于 1,醉汉向东移动,依此类推。

编写一个程序,接受一个整数参数 N 并模拟随机步行者的运动 N 步。在每一步之后,打印随机游走者的位置,将灯柱视为原点 (0, 0)。此外,打印到原点的最终平方距离。

到目前为止,我想出了:

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

但是当我测试这段代码时,我得到 None 作为输出。

我将感谢您对本练习的任何帮助。

4

2 回答 2

5

这是一个好的开始。

主要问题是你没有打电话randint

    a = random.randint

这只是a变成random.randint. 相反,它应该是

    a = random.randint(0, 3)

另外,你重复if a == 3:两次。

此外,设置xy归零应该在函数内部完成,而不是在外部完成。

最后,您的循环(顺便说一下,一次迭代太短)并不能真正起到循环的作用,因为您总是return在第一次迭代期间。

PS这里给你一个小小的离别谜题。弄清楚以下是如何工作的:

dx, dy = random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
x += dx
y += dy
于 2014-10-04T18:25:22.993 回答
0
def randomWalk(steps):
    x = 0  # Make sure you initialize the position to 0,0 each time the function is called
    y = 0
    directions = ['N', 'E', 'S', 'W']  # To keep track of directions, you could use strings instead of 0, 1, 2, 3.
    for i in range(steps):
        a = random.choice(directions)  # You can use random.choice to choose a dir
        if a == 'N':
            y += 1
            print('Current position: ({},{})'.format(x,y))  # You can print the position using format
        elif a == 'S':
            y -= 1
            print('Current position: ({},{})'.format(x,y))
        elif a == 'E':
            x += 1
            print('Current position: ({},{})'.format(x,y))
        else:
            x -= 1
            print('Current position: ({},{})'.format(x,y))

测试

>>> randomWalk(8)
Current position: (0,-1)
Current position: (1,-1)
Current position: (1,0)
Current position: (1,-1)
Current position: (0,-1)
Current position: (-1,-1)
Current position: (-1,0)
Current position: (0,0)
于 2014-10-04T18:31:14.883 回答