Choubada
Choubada

Reputation: 13

Find surrounding elements in a 2d list

So I need a function to return all elements neighbouring a certain index for a 2d list

arr = [
 [1 , 2,  3,  4,  5],
 [6,  7,  8,  9,  10],
 [11, 12, 13, 14, 15],
 [16, 17, 18, 19, 20],
 [21, 22, 23, 24, 25]
]

def ray(arr: list, center: list, ray: int) -> list:
    values = []

    for index_y, value_y in enumerate(arr):
        for index_x, value_x in enumerate(value_y):

            if index_x - center[0] < ray and index_y - center[1] < ray:
                values.append(value_x)
    return values

print(ray(arr, [4,4], 1))

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] it's incorrect, can someone help me or tell me why my function is not working ?

Upvotes: 0

Views: 203

Answers (1)

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

The error lies in
if index_x - center[1] < ray and index_y - center[0] < ray:
If you're comparing distances, you should use absolute values. It should've been
if (abs(index_x - center[1]) < ray) and (abs(index_y - center[0]) < ray):

Upvotes: 2

Related Questions