Python:实现searching in sorted matrix在排序矩阵中搜索算法(附完整源码)

51CTO 2022-08-06 09:34:18 阅读数:752

Python实现searchingmatrixsorted


Python:实现searching in sorted matrix在排序矩阵中搜索算法

from __future__ import annotations


def search_in_a_sorted_matrix(
mat: list[ list], m: int, n: int, key: int | float
) - > None:

i, j = m - 1, 0
while i >= 0 and j < n:
if key == mat[ i][ j]:
print( f"Key { key} found at row- { i + 1} column- { j + 1} ")
return
if key < mat[ i][ j]:
i -= 1
else:
j += 1
print( f"Key { key} not found")


def main():
mat = [[ 2, 5, 7], [ 4, 8, 13], [ 9, 11, 15], [ 12, 17, 20]]
x = int( input( "Enter the element to be searched:"))
print( mat)
search_in_a_sorted_matrix( mat, len( mat), len( mat[ 0]), x)


if __name__ == "__main__":
import doctest

doctest. testmod()
main()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.


版权声明:本文为[51CTO]所创,转载请带上原文链接,感谢。 https://blog.51cto.com/u_11929818/5551015