Reputation: 87
I am trying to write a script using python to solve a maze problem by the right hand method. I have written the below script to read in a file of the maze and put it into numpy 2D array. Now, I would like to search the first row of the array and find the 0. This 0 is the starting point of the maze. From here I would apply my maze algorithm to check the squares sourronding that point on whether or not they have a 1 or 0.
Maze_matrix is the matrix containing my maze and I want to find the index of the first 0 in the first row.
#!/usr/bin/python
import sys
import numpy as np
import itertools
if len(sys.argv) == 3:
maze_file = sys.argv[1]
soln_file = sys.argv[2]
rows = []
columns = []
with open(maze_file) as maze_f:
for line in maze_f:
row, column = line.split()
row = int(row)
column = int(column)
rows.append(row)
columns.append(column)
maze_matrix = np.zeros((rows[0], columns[0]))
for line1, line2 in zip(rows[1:], columns[1:]):
maze_matrix[line1][line2] = 1
print maze_matrix
else:
print('Usage:')
print(' python {} <maze file> <solution file>'.format(sys.argv[0]))
sys.exit()
Upvotes: 1
Views: 1428
Reputation: 10992
I would suggest using numpy.where(). It has a very good performance and searches through your whole array (or a subset) at once. If the condition is true for an element, it returns an array with the index of that element.
In [1]: import numpy as np
In [2]: a = np.random.randint(0, 9, (4,4))
In [8]: a
Out[8]:
array([[6, 5, 0, 3],
[4, 5, 8, 6],
[0, 3, 4, 4],
[6, 4, 6, 7]])
In [9]: np.where(a == 0)
Out[9]: (array([0, 2]), array([2, 0])) # two 0's found
# first at a[0, 2] (row 0, column 2)
# second at a[2, 0] (row 2, column 0)
Upvotes: 1
Reputation: 898
I would suggest taking a look at the numpy.array method argmin
:
>>> n = numpy.ones(100)
>>> n[50] = 0
>>> n.argmin()
50
Upvotes: 1