
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Next Nearest Element in a Matrix Using Python
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.
Advertisements