簡體   English   中英

隨機游走(Python 速成課程)陷入似乎是一個循環的狀態

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

我正在閱讀 Python 速成課程書,但我不知道如何解決隨機游走部分的問題。 當我運行代碼時,命令提示符卡在“處理”模式下,除非我關閉 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 最后幾行的標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM