Random Walk(Python Crash Course) 陷入了一个循环

Random Walk(Python Crash Course) stuck in what seems to be a loop

我正在学习 Python 速成课程书,但我不知道如何解决随机游走部分的问题。当我 运行 代码时,命令提示符卡在 "processing" 模式”,除非关闭 window,否则我无法离开,即

起初我以为可能是我把路径弄得太长了,但即使只有 5 步,代码似乎也不起作用。

这是 class RandomWalk 的代码:

    from random import choice
    class RandomWalk():
    """A class to generate random walks."""

    def __init__(self,num_points=5):
        """Initialize attributes of a walk"""
        self.num_points = num_points

        #All walks start at (0,0).
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """"Calculate all the points in the walk"""

        #Keep taking steps until the walk reaches the desired length
        while len(self.x_values) < self.num_points:
        #Decide which direction to go and how far to go there
            x_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step  = x_direction * x_distance

            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance

        #Reject moves that go nowhere
            if x_step == 0 and y_step == 0:
                continue

        #Calculate the next x and y values
        next_x = self.x_values[-1] + x_step
        next_y = self.y_values[-1] + y_step

        self.x_values.append(next_x)
        self.y_values.append(next_y)

这是 运行 RandomWalk 的代码:

import matplotlib.pyplot as plt

from random_walk import RandomWalk

#Make a random walk, and plot the points.

rw = RandomWalk(5)
rw.fill_walk()

plt.scatter(rw.x_values, rw.y_values, s=15)
plt(show)

我希望代码的结果是一个 matplot 视图,显示随机 5 步步行。

感谢您的帮助!

您永远不会在 while 循环中更新 x_valuesnum_points,因此您创建了一个无限循环。

我想你错过了 RandomWalk 最后几行的标签 class