Python Forum

Full Version: Identifying the value of all adjacent elements in an array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.


Consider the following array:

Output:
m = [['*' '*' '*' '*' '*'] ['*' '*' '*' '*' '*'] ['*' 'O' '*' '*' '*'] ['*' '*' '*' '*' '*'] ['*' '*' '*' '*' '*']]
I want to be able to identify if any elements that are horizontal or vertical neighbours to 'O' (not diagonal neighbours) are also of value 'O'.

So far, I can only think of a rather brute force method, whereby I construct if statements using all possible combinations of up, down, left and right. As an example:

l = []
x = 1
y = 2
#(It is a char array, which is why the y and x are that way around in the indexing.)
if m[y + 1, x] and m[y-1, x] and [y, x - 1] and [y, x + 1] == 'O': #Check if all 4 neighbours are 'O'
    l.append((x, y + 1))
    l.append((x, y - 1))
    l.append((x + 1, y))
    l.append((x - 1, y))
elif m[y + 1, x] and m[y - 1, x] and [y, x - 1] == 'O': #Check if only some combination of 3 neighbours are 'O'
    l.append((x, y + 1))
    l.append((x, y - 1))
    l.append((x - 1, y))
elif m[y + 1, x] and m[y - 1, x] = 'O': #Check if only some combination of 2 neighbours are 'O'
    l.append((x, y + 1))
    l.append((x, y - 1))
elif m[y + 1, x] = 'O': #Check if only one of the neighbours is 'O'
    l.append((x, y + 1))
...
...
...
There are 20 possible combinations, so this would obviously take ages to write out and is unacceptable practice.

Does anyone have any ideas of a method to check if all horizontal and vertical neighbours of 'O' are also 'O', and if so then append to the list?
This function is used to compute a list of horizontal, vertical and diagonal neighbours in a 10x10 array:

X = 10
Y = 10
neighbours = lambda x, y : [(x2-1, y2-1) for x2 in range(x-1, x+2) for y2 in range(y-1, y+2) if (-1 < x <= X+1 and -1 < y <= Y+1 and (x != x2 or y != y2) and (0 <= x2 <= X+1) and (0 <= y2 <= Y+1))]
However, I don't want to see the diagonal neighbours. How can I modify this code so that it only considers the horizontal and vertical neighbours?