Class activity solutions

Author

Ciaran Evans

Here is full code for the roulette simulation:

import numpy as np

np.random.seed(279)

nsim = 1000
results = np.zeros(nsim)
wheel = ["green"]*2 + ["black"]*18 + ["red"]*18

for i in range(nsim):
    money = 50
  
    while(0 < money < 100):
        spin = np.random.choice(wheel, size = 1)
        if spin == "red":
            money = money + 1
        else:
            money = money - 1
    
    results[i] = money == 100

np.mean(results)
0.007

Notes:

Other ways of coding

  • money = money + 1 can be written as money += 1
  • money = money - 1 can be written as money -= 1
  • The if...else... statement can be rewritten in a sample line:
money = money + 1 if spin == "red" else money - 1