Reputation: 18242
I have a maze:
||||||||||||||||||||||
| || | | . |
| |||||| | |||||| |
|||||| | |
| | |||||| || |||||
| |||| | | |
| ||| ||| | |
|||||||||| |||||| |
| P || |
||||||||||||||||||||||
along with the following code:
import numpy
import copy
import collections
UP = [0,1]
DOWN = [0,-1]
LEFT = [-1,0]
RIGHT = [1,0]
theProblem = numpy.empty((rows,cols), dtype=object)
## code to generate the below matrix ##
[['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|'
'|' '|' '|' '|']
['|' ' ' '|' '|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' ' ' '|' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' '|' '|' '|' '|' '|' '|' ' ' '|' ' ' '|' '|' '|' '|'
'|' '|' ' ' '|']
['|' '|' '|' '|' '|' '|' ' ' ' ' ' ' ' ' ' ' 'P' ' ' ' ' '|' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' '|' ' ' '|' '|' '|' '|' '|' '|' ' ' '|' '|' ' ' '|'
'|' '|' '|' '|']
['|' ' ' '|' '|' '|' '|' ' ' '|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|'
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' '|' '|' ' ' '|' '|' '|' ' ' ' '
' ' '|' ' ' '|']
['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' ' ' ' ' ' ' ' ' '|' '|' '|' '|'
'|' '|' ' ' '|']
['|' '.' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' '|' ' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|'
'|' '|' '|' '|']]
#######################################################################
# stateX = location of P[0] #
# stateY = location of P[1] #
print "WALL" if theProblem[stateX+DOWN[0],stateY+DOWN[1]] == '|' else "GO"
Is there a cleaner way to do the last line comparison? I'm pretty new to numpy
, but it seems there has to be a more clever way to compare surrounding cells without explicitly doing like:
print "WALL" if theProblem[stateX+DOWN[0],stateY+DOWN[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+UP[0],stateY+UP[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+LEFT[0],stateY+LEFT[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+RIGHT[0],stateY+RIGHT[1]] == '|' else "GO"
Upvotes: 2
Views: 85
Reputation: 572
# if diagonal movements are accepted
neighbours = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1))
# if diagonal movements are NOT accepted
neighbours = ((0, -1), (-1, 0), (1, 0), (0, 1))
for neighbour in neighbours:
if theProblem[stateX + neighbour[0], stateY + neighbour[1]] == '|':
print "WALL"
else:
print "GO"
Should be equivalent. This is pure Python. I don't know NumPy.
Edit: Another option (for all 8 directions):
for x in range(-1,2):
for y in range(-1,2):
if (x, y) != (0, 0):
if theProblem[stateX + x, stateY + y] == '|':
print "WALL"
else:
print "GO"
Upvotes: 3
Reputation: 1045
What about:
print "WALL" if ("|" in theProblem[stateX+DOWN[0],stateY+DOWN[1]] + theProblem[stateX+UP[0],stateY+UP[1]] + theProblem[stateX+RIGHT[0],stateY+RIGHT[1]] + theProblem[stateX+LEFT[0],stateY+LEFT[1]]) else "GO"
Upvotes: 0