Python 醉汉

2024-05-16 08:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我得写一个代码来计算醉汉走路的路线和长度。在

过度: 一个醉汉从灯柱开始漫无目的地走。在每一个时间步,他随机采取一步,或北,东,南,或西。酒鬼要走多远 从灯柱上走了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()))

但当我测试这段代码时,我没有得到任何输出。在

如果有人帮我解决这个问题,我会很感激的。在


Tags: 代码returnif时间random路线print步态
2条回答
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))

测试

^{pr2}$

这是个好的开始。在

主要问题是无法调用^{}

    a = random.randint

这只会将a转换为random.randint的别名。相反,它应该是

^{pr2}$

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

另外,将xy设置为零应该在函数内部完成,而不是在外部。在

最后,您的循环(顺便说一句,这是一个太短的迭代)并不是真正的循环,因为在第一次迭代中总是return。在

附言:这里有一个小拼图给你。弄清楚以下是如何工作的:

dx, dy = random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
x += dx
y += dy

相关问题 更多 >