I want to get idexes of elemenent into 2d array by square shape
Some more info: Let's pretend that i need get indexes of one element of 2d array
22 33 15
65 32 16
84 26 12
Index of '33' is 01 I want get all nearest elements of it, its: 22, 65, 32, 16, 15 and indexes is: 00, 10, 11, 12, 02
So, i want get indexes like that of any element of array
So x2, for 00 elemnts its 3 neighbor, for 01 its 5 and for 11 its 8 neighbors
And some more: How can i handle out of index value?
Sorry for my bad english
CodePudding user response:
Try this:
# example 2d arr
arr = [[22, 33, 15], [65, 32, 16], [84, 26, 12]]
# print
for row in arr:
for col in row:
print(col, end = " ")
print()
def getNeighbours(x, y, arr):
string = f'({x}, {y}): {arr[y][x]}'
neighbours = []
# get lengths for if check
col_length = len(arr)
row_length = len(arr[0])
# distance options for x, y; loop
for x_distance in [-1, 0, 1]:
for y_distance in [-1, 0, 1]:
# 0 and 0 == cur_position, so exclude
# new x/y < 0 would be out of bounds, so exclude
# new x/y == respective length would be out of bounds, so exclude
# all else ok, hence: 'if not'
if not ((x_distance == 0 and y_distance == 0) or \
(y y_distance < 0 or y y_distance == col_length) or \
(x x_distance < 0 or x x_distance == row_length)):
neighbours.append(arr[y y_distance][x x_distance])
return string, neighbours
# tests
result = getNeighbours(1, 0, arr)
print(result)
result = getNeighbours(1, 1, arr)
print(result)
result = getNeighbours(2, 1, arr)
print(result)
Output:
22 33 15
65 32 16
84 26 12
('(1, 0): 33', [22, 65, 32, 15, 16])
('(1, 1): 32', [22, 65, 84, 33, 26, 15, 16, 12])
('(2, 1): 16', [33, 32, 26, 15, 12])