查找矩阵中下一个最近元素的Python程序
给定一个矩阵、一组坐标和一个元素,任务是编写一个Python程序,该程序可以获取下一次出现元素的坐标。
Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 1, 3, K = 3
Output : (1, 4)
Explanation : After (1, 3), 3 is found at (1, 4)
Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 2, 3, K = 3
Output : (2, 4)
Explanation : After (2, 3), 3 is found at (2, 4)
方法:使用循环和枚举()
在这里,我们从所需的坐标开始迭代,并在从 row + 1, col + 1 到 N, N 坐标形成的矩形内检查下一个最近的 K。如果未找到,则返回 -1、-1。
例子:
Python3
# get Nearest coord.
def near_coord(test_list, x, y, val):
for idx, row in enumerate(test_list[x:]):
for j, ele in enumerate(row):
# checking for value at lower formed rectangle
if ele == val and j > y:
return idx + x, j
# if no index found
return -1, -1
# initializing list
test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3],
[8, 5, 3, 5, 3], [1, 2, 3, 4, 6]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check coord
i, j = 1, 3
# initializing K
K = 3
# getting nearest coordinates
res_abs, res_ord = near_coord(test_list, i, j, K)
# printing result
print("Found K index : " + str((res_abs, res_ord)))
输出:
The original list is : [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]]
Found K index : (1, 4)