All elements greater than its neighbors

... by Bittle in Programming Help January 11, 2021

Question:

Write function receive a matrix 

Checks for each number in the matrix whether its value is larger than all its neighbors

(Neighbors of an number are the numbers adjacent to it, Up, down right, left, diagonals)


The function will print the numbers in the matrix that larger than their neighbors

And return a counter that count how many number fulfills the condition


(Numpy must not be used)


Examples:

# input
mat = [[2, 3, 4, 5, 6],
       [6, 5, 7, 4, 3],
       [3, 4, 9, 8, 2],
       [5, 4, 8, 7, 6],
       [1, 2, 9, 5, 9]]

# output
1. matr[0][4]=6 > (5, 4, 3)
2. matr[1][0]=6 > (3, 4, 5, 3, 2)
3. matr[2][2]=9 > (5, 4, 4, 8, 7, 8, 4, 7)
4. matr[3][0]=5 > (1, 2, 4, 4, 3)
5. matr[4][2]=9 > (4, 2, 5, 7, 8)
6. matr[4][4]=9 > (7, 5, 6)


count = 6


Solution:

# return True if matrix[row][col] exists (row, column is in bounds)
def in_bounds(matrix, row, col):
    if row < 0 or col < 0:
        return False
    if row > len(matrix) - 1 or col > len(matrix) - 1:
        return False
    return True


def get_neighbors(matrix, x, y):
    # get the surrounding indices
    neighbors_arr = [[x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x + 1, y], [x + 1, y + 1], [x, y + 1], [x - 1, y + 1],
                     [x - 1, y]]
    # check if indices are in bounds and return the list
    return [matrix[n[0]][n[1]] for n in neighbors_arr if in_bounds(matrix, n[0], n[1])]


# returns true if element is greater than all the values in list_, false otherwise
def greater_than_all(element, list_):
    for e in list_:
        if e >= element:
            return False

    return True


# param: matrix
# return: number of elements which are greater than all their neighbors
def count_greater(matrix):
    count_ = 0
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            neighbors = get_neighbors(matrix, i, j)
            if greater_than_all(matrix[i][j], neighbors):
                count_ += 1
                print("{0}. matr[{1}][{2}]={3} > ({4})".format(count_, i, j, matrix[i][j],
                                                               ', '.join(map(str, neighbors))))

    return count_


if __name__ == '__main__':
    mat = [[2, 3, 4, 5, 6],
           [6, 5, 7, 4, 3],
           [3, 4, 9, 8, 2],
           [5, 4, 8, 7, 6],
           [1, 2, 9, 5, 9]]

    print("\ncount = {0}".format(count_greater(mat)))


Solution 2 (requested without .join() or .format())

# return True if matrix[row][col] exists (row, column is in bounds)
def in_bounds(matrix, row, col):
    if row < 0 or col < 0:
        return False
    if row > len(matrix) - 1 or col > len(matrix) - 1:
        return False
    return True


def get_neighbors(matrix, x, y):
    # get the surrounding indices
    neighbors_arr = [[x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x + 1, y], [x + 1, y + 1], [x, y + 1], [x - 1, y + 1],
                     [x - 1, y]]
    # check if indices are in bounds and return the list
    return [matrix[n[0]][n[1]] for n in neighbors_arr if in_bounds(matrix, n[0], n[1])]


# returns true if element is greater than all the values in list_, false otherwise
def greater_than_all(element, list_):
    for e in list_:
        if e >= element:
            return False

    return True


def array_to_string(arr_):
    f_string = ""
    for a in arr_:
        f_string += " " + str(a)

    return f_string.strip().replace(" ", ", ")


# param: matrix
# return: number of elements which are greater than all their neighbors
def count_greater(matrix):
    count_ = 0
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            neighbors = get_neighbors(matrix, i, j)
            if greater_than_all(matrix[i][j], neighbors):
                count_ += 1
                print(str(count_)+". matr["+str(i)+"]["+str(j)+"]="+str(matrix[i][j])+" > ("+array_to_string(neighbors)+")")

    return count_


if __name__ == '__main__':
    mat = [[2, 3, 4, 5, 6],
           [6, 5, 7, 4, 3],
           [3, 4, 9, 8, 2],
           [5, 4, 8, 7, 6],
           [1, 2, 9, 5, 9]]

    print("\ncount = "+str(count_greater(mat)))


Comments (0)

Search Here