Answer the question
In order to leave comments, you need to log in
Python. Check if element a and b are next to each other in a multidimensional list (matrix)?
There is a matrix of the form:
That is, it consists of nested lists with numbers. You need to check if element A is next to element B. A is next to B if B is to the right or left of it, or above / below or diagonally from it.
For example, in a matrix:
Element 2 next to 5, 7 next to 10 (tk diagonally) and etc.
Answer the question
In order to leave comments, you need to log in
For example, like this:
import numpy as np
from itertools import zip_longest
lst =
def neighbors(a, b, m=lst, r=1):
m = np.array(list(zip_longest(*m)))#.T
v = np.argwhere(m == b) - np.argwhere(m == a)
return np.abs(v).max() <= r
assert neighbors(1, 2) == True
assert neighbors(1, 6) == False
assert neighbors(5, 6) == True
assert neighbors(3, 6) == True
assert neighbors(7, 11) == True
assert neighbors(1, 9) == False
assert neighbors(7, 8) == True
If both indexes A do not differ from indexes B by more than 1.
Although I did not understand exactly how you count the "diagonal" given the unequal length of the lines.
def func(arr, a, b):
for elem1 in range(len(arr)):
for elem2 in range(len(arr[elem1])):
if arr[elem1][elem2] == a:
onePositionA = arr.index(arr[elem1])
twoPositionA = arr[elem1].index(arr[elem1][elem2])
elif arr[elem1][elem2] == b:
onePositionB = arr.index(arr[elem1])
twoPositionB = arr[elem1].index(arr[elem1][elem2])
if abs(onePositionA - onePositionB) <= 1 and abs(twoPositionA - twoPositionB) <= 1:
return True
else:
return False
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question