-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleela scipython elegant.py
More file actions
102 lines (84 loc) · 1.98 KB
/
Copy pathleela scipython elegant.py
File metadata and controls
102 lines (84 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 15:25:34 2020
@author: rcxsm
"""
#https://scipython.com/book/chapter-6-numpy/additional-problems/analysing-snakes-and-ladders-as-a-markov-chain/
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#ladders = [(3,19), (15,37), (22,42), (25,64), (41,73),
# (53,74), (63,86), (76,91), (84,98)]
#snakes = [(11,7), (18,13), (28,12), (36,34), (77,16),
# (47,26), (83,39), (92,75), (99,70)]
#trans = ladders + snakes
laddersx = [(9,22),(16,68),(19,31),(
21,59),(
26,40),(
27,49),(
44,66),(
36,65),(
45,61),(
53,67)]
snakesx = [(62,1),(
54,2),(
15,3),(
28,5),(
23,6),(
11,7),(
43,8),(
51,34),(
72,51)]
ladders = [
(1,38),
(4,14),
(9,31),
(21,42),
(28,84),
(36,44),
(51,67),
(71,91),
(80,100)]
snakes = [(16,6),
(47,26),
(49,11),
(56,53),
(62,19),
(64,60),
(87,24),
(93,73),
(95,75),
(98,78)]
trans = ladders + snakes
# Set up the transition matrix
T = np.zeros((101, 101))
for i in range(1,101):
T[i-1,i:i+6] = 1/6
for (i1,i2) in trans:
iw = np.where(T[:,i1] > 0)
T[:,i1] = 0
T[iw,i2] += 1/6
# House rules: you don't need to land on 100, just reach it.
T[95:100,100] += np.linspace(1/6, 5/6, 5)
for snake in snakes:
T[snake,100] = 0
# The player starts at position 0.
v = np.zeros(101)
v[0] = 1
n, P = 0, []
cumulative_prob = 0
# Update the state vector v until the cumulative probability of winning
# is "effectively" 1
while cumulative_prob < 0.99999:
n += 1
v = v.dot(T)
P.append(v[100])
cumulative_prob += P[-1]
mode = np.argmax(P)+1
print('modal number of moves:', mode)
# Plot the probability of winning as a function of the number of moves
fig, ax = plt.subplots()
ax.plot(np.linspace(1,n,n), P, 'g-', lw=2, alpha=0.6, label='Markov')
ax.set_xlabel('Number of moves')
ax.set_ylabel('Probability of winning')
plt.show()