Reputation: 13
I have two 3D Numpy array
win_combination = np.array([
[[0, 0], [0, 1], [0, 2]],
[[1, 0], [1, 1], [1, 2]],
[[2, 0], [2, 1], [2, 2]],
[[0, 0], [1, 0], [2, 0]],
[[0, 1], [1, 1], [2, 1]],
[[0, 2], [1, 2], [2, 2]],
[[0, 0], [1, 1], [2, 2]],
[[0, 2], [1, 1], [2, 0]]
])
and,
game_log = np.array([[1 1],[0 2],[1 0]])
I would like to compare if the game_log data matches any of the arrays in win_combination if it matches it may print True else print False.
Basically I want that if game_log == [[0, 0],[0, 1],[0, 2]] it may print True if it isn't then my code should compare another array game_log == [[1, 0], [1, 1], [1, 2]] if not then #another and so on till last and print false if there is no array that matches game_log and in this case it should print False
I have tried,
for comb in win_combination:
if game_log == comb:
print(True)
else:
print(False)
Upvotes: 0
Views: 131
Reputation: 93
Try this method:
def in_array(game_log, array):
for comb in array:
for arr in comb:
if game_log.all() == arr.all():
return True
return False
Pass the game_log to the first argument and the 3D to the next one, based on what i understand it should print True if the combination is in the array and False otherwise.
Keep in mind that the truth value of an array with more than one element is ambiguous. So its best to use all() if both arrays are exact matches and any() if any element in one array exists in the other.
Upvotes: 0
Reputation: 4618
IIUC:
ans = np.any(np.all(game_log == win_combination, axis=(1,2)))
print(ans)
Upvotes: 0
Reputation: 114230
Two arrays are equal if np.all(x == y)
(or alternatively (x == y).all()
). You have a 3D array of shape (N, A, B)
and a 2D array of shape (A, B)
. In this case, N=8
, A=3
and B=2
. These shapes broadcast to the shape of the 3D array. If you apply np.all
to the last two dimensions, you can get N
True
or False
values for each of the combinations. np.any
will then tell you if any of them are True
.
all
has an axis
keyword. As of numpy 1.7.0, axis
can specify more than one axis simultaneously, so you can do:
matches = np.all(win_combination == game_log, axis=(-1, -2))
For older versions of numpy, you would have to reshape to get a single axis, or apply all
twice:
matches = np.all((win_combination == game_log).reshape(win_comination.shape[0], -1), axis=-1)
OR
matches = np.all(np.all(win_combination == game_log, axis=-1), axis=-1)
The final result is matches.any()
or np.any(matches)
. You can write it as a one-liner:
np.all(win_combination == game_log, axis=(-1, -2)).any()
Upvotes: 1