Nenhuma Descrição

random_walk.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from random import choice
  2. class RandomWalk():
  3. """A class to generate random walks."""
  4. def __init__(self, num_points=5000):
  5. """Initialize attributes of a walk."""
  6. self.num_points = num_points
  7. # All walks start at (0, 0).
  8. self.x_values = [0]
  9. self.y_values = [0]
  10. def fill_walk(self):
  11. """Calculate all the points in the walk."""
  12. # Keep taking steps until the walk reaches the desired length.
  13. while len(self.x_values) < self.num_points:
  14. # Decide which direction to go, and how far to go in that direction.
  15. x_direction = choice([1, -1])
  16. x_distance = choice([0, 1, 2, 3, 4])
  17. x_step = x_direction * x_distance
  18. y_direction = choice([1, -1])
  19. y_distance = choice([0, 1, 2, 3, 4])
  20. y_step = y_direction * y_distance
  21. # Reject moves that go nowhere.
  22. if x_step == 0 and y_step == 0:
  23. continue
  24. # Calculate the next x and y values.
  25. next_x = self.x_values[-1] + x_step
  26. next_y = self.y_values[-1] + y_step
  27. self.x_values.append(next_x)
  28. self.y_values.append(next_y)