'Why is the Markov chain repeating itself?

I am trying to simulate Markov chains using classes in Python. Here is my code:

import random
...
class Chain:
  def __init__(self, probabilities, start):
    self.probs = probabilities
    self.start = start
    self.names = list(self.probs.keys())

  def __iter__(self):
    self.pos = self.start
    return self

  def __next__(self):
    self.random_num = random.randrange(100)

    prob_l = self.probs[self.pos]
    for ind, prob in enumerate(prob_l):
      self.prob_sum += prob
      if self.random_num < self.prob_sum:
        exclude_names = self.names[:ind] + self.names[ind + 1 :]
        self.prob_sum = 0
        self.pos = exclude_names[ind]
        return self.pos
    return self.pos


chain = Chain({"A": [50, 25], "B": [50, 25], "C": [50, 50]}, "A")
chain_iter = iter(chain)
for k in range(100):
    print(next(chain_iter))

It kind of works as expected, but it sometimes will repeat the letter C. Because of the two 50s in the dictionary, it should have a 50/50 chance of going to A or B. It should never repeat.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source