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)
Notes:
- This code takes advantage of some properties of Python lists: lists can be “added” together to combine them, and “multiplying” will repeat them
- Be careful with indenting. Remember that whitespace is important in Python!
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