import numpy as np import matplotlib.pyplot as plt bridges = ['TGGGG', 'TTGGG', 'GGGGG'] ps = [0.2, 0.2, 0.6] trials = [] while len(trials) < 100000: bridge = np.random.choice(bridges, p=ps) creature = np.random.choice(list(bridge)) if creature == 'T': if bridge.count('T') == 1: trials.append(1) else: trials.append(0) cumulative_fractions = np.cumsum(trials) / (np.arange(len(trials)) + 1.) plt.semilogx(cumulative_fractions) plt.ylim(0, 1) plt.axhline(1. / 3, color='red', linestyle='--') plt.xlabel('Number of trials') plt.ylabel('Cumulative fraction of safe passages'); %timeit np.random.choice(bridges, p=ps)