简体   繁体   中英

Removing specific subarrays in numpy

I am working with a numpy array that stores a specific state of a game and I am searching through that state space by 'expanding' the current state and creating a new array that stores the possible states that can be reached from the current state. To avoid search loops, I need to remove any arrays that resulted from invalid moves (if an invalid move is made, the resulting state is equal to the current state).

To accomplish this I am attempting to use numpy.where :

invalid_moves = np.where(np.array_equal(state, current_state) for state in successors)
successors = np.delete(successors, invalid_moves, axis=0) 
#successors is an (s, n, n) array where s is the number of states possible 
#from a given current state and each state is (n, n)

However when the current state has no possible invalid moves, and no possible states should be removed from the successors, the first state is always removed. Can anyone help explain why this is or perhaps where I went wrong?

The issue can be illustrated by a dummy example. Here s are your successors, and we use state>100 as a current state.

a = numpy.arange(10)
successors = [a.copy(), a.copy(), a.copy()]

numpy.where(numpy.array_equal(state, state>100) for state in successors)
>>> (array([0], dtype=int64),)

The array with element 0 is responsible for the deletion in the next step.

Assuming that successors is a list, we get:

[numpy.array_equal(i, i>100) for i in successor]
>>> [False, False False]

For which numpy.where simply returns the first element.

To avoid the issue, check whether or not any of the states matched, and if none did, don't perform the deletion.

a = [np.array_equal(state, current_state) for state in successors]
if any(a):
    invalid_moves = np.where(a)
    successors = np.delete(successors, invalid_moves, axis=0) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM