I'm new to python and I don´t understand the last line of this python code. What does it mean?
import np as numpy
def goat_door(prizedoors, guesses):
#strategy: generate random answers, and
#keep updating until they satisfy the rule
#that they aren't a prizedoor or a guess
result = np.random.randint(0, 3, prizedoors.size)
while True:
bad = (result == prizedoors) | (result == guesses)
if not bad.any():
return result
result[bad] = np.random.randint(0, 3, bad.sum())
prizedoors and guesses are np.random.choice(2,number of simulations)
Result is an array and I don´t know what result[bad] means.
Edit: I've just write import np as numpy
result
is a numpy ndarray
of length prizedoors.size
, where each element is randomly drawn from [0, 3)
. For example:
>>> result = np.random.randint(0, 3, 5)
>>> result
array([1, 1, 2, 0, 1])
bad
is a boolean array which is True wherever result == prizedoors
or result == guesses
. Probably prizedoors
and guesses
are boolean arrays too. In any case, bad
will wind up looking something like
>>> bad
array([ True, True, True, False, True], dtype=bool)
bad.sum()
counts the number of Trues:
>>> bad.sum()
4
result[bad]
selects the elements of result
where bad == True
:
>>> result[bad]
array([1, 1, 2, 1])
and finally, the last line fills the bad values with new random values (not necessarily good values, only new ones):
>>> result[bad] = np.random.randint(0, 3, bad.sum())
>>> result
array([1, 1, 0, 0, 1])