Python Program to find the Next Nearest element in a Matrix

PythonServer Side ProgrammingProgramming

When it is required to find the next nearest element in a matrix, a method is defined tat iterates through the list and places a specific condition. This method is called and the results are displayed.

Example

Below is a demonstration of the same

def get_nearest_elem(my_list, x, y, my_key):
   for index, row in enumerate(my_list[x:]):
      for j, elem in enumerate(row):

         if elem == my_key and j > y:
            return index + x, j

   return -1, -1

my_list = [[21, 32, 11, 22, 13], [91, 52, 31, 26, 33], [81, 52, 3, 22, 3], [11, 92, 83, 4, 9]]

print("The list is :")
print(my_list)

i, j = 1, 3
my_key = 3

my_res_abs,my_res_ord = get_nearest_elem(my_list, i, j, my_key)

print("The found K index is :")
print(my_res_abs, my_res_ord)

Output

The list is :
[[21, 32, 11, 22, 13], [91, 52, 31, 26, 33], [81, 52, 3, 22, 3], [11, 92, 83, 4, 9]]
The found K index is :
2, 4

Explanation

  • A method named ‘get_nearest_elem’ is defined that takes a list, a key and two integers as parameters.

  • The list is iterated over using enumeration and if the element and the key match, the index value summed with the integer is returned.

  • Outside the method, a list of list is defined and is displayed on the console.

  • Two integers are defined.

  • A key value is defined.

  • The method is called by passing the required parameters.

  • The output is displayed on the console.

raja
Published on 15-Sep-2021 11:42:27
Advertisements