[Python] Find neighbors in a matrix?

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página