forked from Kaggle/learntools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex5.py
More file actions
167 lines (139 loc) · 6.21 KB
/
Copy pathex5.py
File metadata and controls
167 lines (139 loc) · 6.21 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import random
from learntools.core import *
class EarlyExitDebugging(FunctionProblem):
_var = 'has_lucky_number'
_test_cases = [
([], False),
([7], True),
([14], True),
([3, 14], True),
([3, 21, 4], True),
([7, 7, 7], True),
([3], False),
([3, 4, 5], False),
]
_hint = ("How many times does the body of the loop run for a list"
" of length n? (If you're not sure, try adding a `print()`"
" call on the line before the `if`.)")
_solution = """Remember that `return` causes a function to exit immediately. So our original implementation always ran for just one iteration. We can only return `False` if we've looked at every element of the list (and confirmed that none of them are lucky). Though we can return early if the answer is `True`:
```python
def has_lucky_number(nums):
for num in nums:
if num % 7 == 0:
return True
# We've exhausted the list without finding a lucky number
return False
```
Here's a one-line version using a list comprehension with Python's `any` function (you can read about what it does by calling `help(any)`):
```python
def has_lucky_number(nums):
return any([num % 7 == 0 for num in nums])
```
"""
class ElementWiseComparison(FunctionProblem):
_var = 'elementwise_greater_than'
_test_cases = [
( ([1, 2, 3, 4], 2), [False, False, True, True] ),
( ([1, 2, 3, 4], 5), [False, False, False, False] ),
( ([], 2), [] ),
( ([1, 1], 0), [True, True] ),
]
_solution = """Here's one solution:
```python
def elementwise_greater_than(L, thresh):
res = []
for ele in L:
res.append(ele > thresh)
return res
```
And here's the list comprehension version:
```python
def elementwise_greater_than(L, thresh):
return [ele > thresh for ele in L]
```
"""
class BoringMenu(FunctionProblem):
_var = 'menu_is_boring'
_test_cases = [
( ['Egg', 'Spam',], False),
( ['Spam', 'Eggs', 'Bacon', 'Spam'], False),
( ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam'], True),
( ['Spam', 'Spam'], True),
( ['Lobster Thermidor aux crevettes with a Mornay sauce, garnished with truffle pâté, brandy and a fried egg on top', 'Spam'], False),
( ['Spam'], False),
( [], False),
]
_hint = ("This is a case where it may be preferable to iterate over the *indices* of the list (using a call to `range()`) rather than iterating over the elements of the list itself. When indexing into the list, be mindful that you're not \"falling off the end\" (i.e. using an index that doesn't exist).")
# TODO: I don't think I want to mention any of the more 'clever' solutions involving zip or itertools. Though it depends on whether
# we end up covering zip in the tutorial notebook.
_solution = """
```python
def menu_is_boring(meals):
# Iterate over all indices of the list, except the last one
for i in range(len(meals)-1):
if meals[i] == meals[i+1]:
return True
return False
```
The key to our solution is the call to `range`. `range(len(meals))` would give us all the indices of `meals`. If we had used that range, the last iteration of the loop would be comparing the last element to the element after it, which is... `IndexError`! `range(len(meals)-1)` gives us all the indices except the index of the last element.
But don't we need to check if `meals` is empty? Turns out that `range(0) == range(-1)` - they're both empty. So if `meals` has length 0 or 1, we just won't do any iterations of our for loop.
"""
# Analytic solution for expected payout =
# .005 * 100 + (.05 - .005) * 5 + (.25 - .05) * 1.5
def play_slot_machine():
r = random.random()
if r < .005:
return 100
elif r < .05:
return 5
elif r < .25:
return 1.5
else:
return 0
# TODO: Could probably make this checkable.
class ExpectedSlotsPayout(ThoughtExperiment):
#_var = 'estimate_average_slot_payout'
_solution = ("The exact expected value of one pull of the slot machine is 0.025"
" - i.e. a little more than 2 cents. See? Not every game in the Python"
" Challenge Casino is rigged against the player!\n\n"
"Because of the high variance of the outcome (there are some very rare "
"high payout results that significantly affect the average) you might need"
" to run your function with a very high value of `n_runs` to get a stable "
"answer close to the true expectation.\n\n"
"If your answer is way higher than 0.025, then maybe you forgot to account for the"
" $1 cost per play?")
class SlotsSurvival(FunctionProblem):
_bonus = True
_var = 'slots_survival_probability'
_solution = CS("""def slots_survival_probability(start_balance, n_spins, n_simulations):
# How many times did we last the given number of spins?
successes = 0
# A convention in Python is to use '_' to name variables we won't use
for _ in range(n_simulations):
balance = start_balance
spins_left = n_spins
while balance >= 1 and spins_left:
# subtract the cost of playing
balance -= 1
balance += play_slot_machine()
spins_left -= 1
# did we make it to the end?
if spins_left == 0:
successes += 1
return successes / n_simulations""")
def check(self, fn):
actual = fn(10, 10, 1000)
assert actual == 1.0, "Expected `slots_survival_probability(10, 10, 1000)` to be 1.0, but was actually {}".format(repr(actual))
actual = fn(1, 2, 10000)
assert .24 <= actual <= .26, "Expected `slots_survival_probability(1, 2, 10000)` to be around .25, but was actually {}".format(repr(actual))
actual = fn(25, 150, 10000)
assert .22 <= actual <= .235, "Expected `slots_survival_probability(25, 150, 10000)` to be around .228, but was actually {}".format(repr(actual))
qvars = bind_exercises(globals(), [
EarlyExitDebugging,
ElementWiseComparison,
BoringMenu,
ExpectedSlotsPayout,
SlotsSurvival,
],
)
__all__ = list(qvars) + ['play_slot_machine']