简体   繁体   English

在 Python 中使用迭代器创建无限随机游走

[英]Create infinite random walk using iterators in Python

I have a practice problem concerning random walks:我有一个关于随机游走的练习问题:

在此处输入图像描述

So far my code looks like this:到目前为止,我的代码如下所示:

import random
import itertools
p = [0,0]

def random_walk():
    yield p
    for _ in itertools.count(0,1):
        sign = random.randrange(-1, 2,2)
        cord = random.randint(0,1)
        p[cord] += sign
        yield p

However, when I run it nothing happens.但是,当我运行它时,什么也没有发生。 I assume it runs too many times too quickly to actually yield anything.我认为它运行太多次太快而无法实际产生任何东西。 Is there any way to fix this so it outputs a sequence like the one in the problem text?有没有办法解决这个问题,所以它输出一个像问题文本中的序列? Just to let you know, I am taking an introductory course to Python focused on scientific applications so my general knowledge of programming, in general, is very limited.只是为了让你知道,我正在参加 Python 的入门课程,重点是科学应用,所以我对编程的一般知识通常非常有限。 Later on in the exercise, I am supposed to use itertools.islice to generate a finite path but I need this to work first.稍后在练习中,我应该使用itertools.islice来生成一个有限路径,但我需要它首先工作。 Any help will be much appreciated!任何帮助都感激不尽!

You have to use your generator to see the results (for example in a for loop).您必须使用生成器来查看结果(例如在 for 循环中)。 Also, a generator should return individial values, not the accumulated list of values so far:此外,生成器应该返回单独的值,而不是到目前为止的累积值列表:

import random
def random_walk():
    x = y = 0
    offsets = [ (0,1),(0,-1),(1,0),(-1,0) ]
    while True:
        yield (x,y)
        dx,dy = random.choice(offsets)
        x,y   = x+dx, y+dy

output: output:

from itertools import islice
print(*islice(random_walk(),10))

(0, 0) (-1, 0) (-1, -1) (0, -1) (0, 0) (-1, 0) (-1, -1) (-2, -1) (-2, -2) (-2, -1)

proof that it is infinite:证明它是无限的:

for point in random_walk(): print(point, end=" ")

(0, 0) (-1, 0) (-1, -1) (-1, -2) (0, -2) (0, -3) (0, -4) (-1, -4) (-2, -4) (-3, -4) (-4, -4) (-4, -5) (-5, -5) (-4, -5) (-3, -5) (-3, -6) (-4, -6) (-4, -7) (-4, -6) (-3, -6) (-3, -7) (-4, -7) (-5, -7) (-4, -7) (-5, -7) (-5, -6) (-4, -6) (-3, -6) (-4, -6) ...

note you have to interrupt this loop with control-C because it is infinite请注意,您必须使用 control-C 中断此循环,因为它是无限的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM