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
1 Answer 1
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])
npobject. Also, I'm not so sure this is correct python, unless I'm missing something entirely.bad = ( ) | ( )will be assigned a boolean value. Booleans in python certainly don't have a.any()function. Is this some sort of pseudo-python interpretation?npappears to be a reference to numpy's random library. See: docs.scipy.org/doc/numpy/reference/generated/…npis referring to numpy, which explains the use or.any()|is the bitwise-or operator which is different from the standard or (||) operator. It is not guaranteed to return a singular boolean value.