Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Menu
Open sidebar
cs1-24fa
lecture-code
Commits
03f49247
Commit
03f49247
authored
4 months ago
by
Adam Blank
Browse files
Options
Download
Email Patches
Plain Diff
Add new file
parent
70a9914a
master
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
14/monty.py
+62
-0
14/monty.py
with
62 additions
and
0 deletions
+62
-0
14/monty.py
0 → 100644
View file @
03f49247
from
collections
import
Counter
from
enum
import
Enum
from
fractions
import
Fraction
import
random
DoorOption
=
Enum
(
'DoorOption'
,
[
'GOAT'
,
'CAR'
])
Situation
=
list
[
DoorOption
]
def
generate_situation
(
N
=
3
)
->
Situation
:
output
:
list
[
DoorOption
]
=
[]
car_index
=
random
.
randint
(
0
,
N
-
1
)
for
i
in
range
(
N
):
output
.
append
(
DoorOption
.
GOAT
)
output
[
car_index
]
=
DoorOption
.
CAR
return
output
def
choose_door
(
situation
:
Situation
,
disallowed
:
set
[
int
]):
choices
=
list
(
range
(
len
(
situation
)))
for
x
in
disallowed
:
choices
.
remove
(
x
)
return
random
.
choice
(
choices
)
def
play_game
(
situation
:
Situation
,
use_switch_strategy
=
True
)
->
bool
:
choice
:
int
=
choose_door
(
situation
,
set
())
car
:
int
=
situation
.
index
(
DoorOption
.
CAR
)
goat
:
int
=
choose_door
(
situation
,
set
([
choice
,
car
]))
if
use_switch_strategy
:
choice
=
choose_door
(
situation
,
set
([
choice
,
goat
]))
return
situation
[
choice
]
==
DoorOption
.
CAR
NUM_DOORS
=
8
games_played
=
0
wins
:
Counter
[
str
]
=
Counter
()
def
actual_probability
(
doors
):
return
str
((
doors
-
1
))
+
'/'
+
str
((
doors
*
(
doors
-
2
)))
+
" = "
+
str
((((
doors
-
1
))
/
((
doors
*
(
doors
-
2
)))))
def
frac
(
num
,
dem
):
return
Fraction
(
num
,
dem
).
limit_denominator
(
NUM_DOORS
*
NUM_DOORS
)
while
True
:
situation
=
generate_situation
(
NUM_DOORS
)
if
play_game
(
situation
,
True
):
wins
[
'switch'
]
+=
1
if
play_game
(
situation
,
False
):
wins
[
'stay'
]
+=
1
games_played
+=
1
if
games_played
%
10000
==
0
:
print
(
"
\033
c"
,
end
=
""
,
flush
=
True
)
print
(
"stay :"
,
frac
(
wins
[
'stay'
],
games_played
),
"= "
+
str
(
wins
[
'stay'
]
/
games_played
))
print
(
"switch (exp):"
,
frac
(
wins
[
'switch'
],
games_played
),
"= "
+
str
(
wins
[
'switch'
]
/
games_played
))
print
(
"switch (act):"
,
actual_probability
(
NUM_DOORS
))
This diff is collapsed.
Click to expand it.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment
Menu
Projects
Groups
Snippets
Help