Search code examples
pythongeneratormarkov-chainsmarkov

Markov chain generator


The generator should take a starting point (an integer). With each pass of the resultant generator object to next, a random step from the last point returned (or the starting point if no point has yet been returned) should be performed. The result of this step should be returned after the step is taken.

import random

def markov(start: int):
  for i in range (1):
     yield random.randint(i-1, i+1)

What is wrong with my code?


Solution

  • You're on the right track. Assuming a step-size of 1 (in either direction), you should be able to get rid of the i counter altogether:

    >>> import random
    >>>
    >>>
    >>> def markov(start: int):
    ...     location = start
    ...     while True:
    ...         yield location
    ...         location += random.randint(-1, 1)
    ...
    >>>
    >>> gen = markov(5)
    >>> next(gen)
    5
    >>> next(gen)
    6
    >>> next(gen)
    5
    >>> next(gen)
    6
    >>> next(gen)
    7
    >>> next(gen)
    6
    >>> next(gen)
    5
    >>> next(gen)
    4
    >>> next(gen)
    4
    >>> next(gen)
    3