Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find neighbors in a matrix?

Tags:

python

Here is a 7x7 matrix:

11  21  31  41  51  61  71
12  22  32  42  52  62  72
13  23  33  43  53  63  73
14  24  34  44  54  64  74
15  25  35  45  55  65  75
16  26  36  46  56  66  76
17  27  37  47  57  67  77

The numbers 11, 21, 33 … are the values of the positions. If a radius, the number of row and the number of column are given, how to find the neighbors?

For example, function neighbors(radius = 1, rowNumber = 3, columnNumber = 3) should return a matrix:

22  32  42
23  33  43
24  34  44

function neighbors(radius = 2, rowNumber = 3, columnNumber = 3) should return a matrix:

11  21  31  41  51
12  22  32  42  52
13  23  33  43  53
14  24  34  44  54
15  25  35  45  55

When the neighbor is out of boundary, its value should be 0. For example, function neighbors(radius = 2, rowNumber = 1, columnNumber = 1) should return a matrix

0   0   0   0   0
0   0   0   0   0
0   0   11  21  31
0   0   12  22  32
0   0   13  23  33

I've been thing about this problem for 3 days, but I still can't develop a solution for it.

like image 679
Cheer Avatar asked Dec 15 '22 00:12

Cheer


1 Answers

It might be hard in other languages but in Python this is quite easy. Here is a function that can do what you asked for:

def neighbors(radius, row_number, column_number):
     return [[a[i][j] if  i >= 0 and i < len(a) and j >= 0 and j < len(a[0]) else 0
                for j in range(column_number-1-radius, column_number+radius)]
                    for i in range(row_number-1-radius, row_number+radius)]

Here is a 2D list:

 a = [[ 11,  21,  31,  41,  51,  61,  71],
      [ 12,  22,  32,  42,  52,  62,  72],
      [ 13,  23,  33,  43,  53,  63,  73],
      [ 14,  24,  34,  44,  54,  64,  74],
      [ 15,  25,  35,  45,  55,  65,  75],
      [ 16,  26,  36,  46,  56,  66,  76],
      [ 17,  27,  37,  47,  57,  67,  77]]

See List comprehensions.

Updated missing "and" in the solution - pls review

like image 175
Gnijuohz Avatar answered Dec 22 '22 01:12

Gnijuohz