mercredi 23 janvier 2019

Problem with random package code in Python

I have the following simple "random walk" code:

import random

def random_walk(n):
    """Return coordinates after 'n' block random walk."""
    x = 0
    y = 0
    for i in range(n):
        step = random.choice(['N', 'S', 'E', 'W'])
        if step == 'N':
            y = y + 1
        elif step == 'S':
            y == y - 1
        elif step == 'W':
            x = x + 1
        else:
            x = x - 1
        return (x,y)

for i in range(25):
    walk = random_walk(10)
    print(walk, "Distance from home = ", abs(walk[0]) + abs(walk[1]))

I have two problems:

(A) When I run this in Visual Studio Code it tells me that variable i is not used. It gets "underlined" giving me the following error:

[pylint] Unused variable 'i' [W0612] (10,6)
[pylint] Unused variable 'i' [W0101] (22,3)

Note that Sublime and Jupyter have no problem running it.

(B) For some reason I never am able to move more than one step in x direction and one in y direction. As a result my distance from home is always 0,1 or But the code above clearly states that we walk for n blocks and not just 0, 1, or 2 blocks.

(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(0, 1) Distance from home = 1
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(1, 0) Distance from home = 1
(0, 0) Distance from home = 0
(0, 0) Distance from home = 0

What is the problem?




Aucun commentaire:

Enregistrer un commentaire