shinemic

有序二维度列表找数

Dec 6th, 2019
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. def find1(arr, tar):
  2.     nrow = len(arr)
  3.     ncol = len(arr[0])
  4.     r, c = nrow - 1, 0
  5.     while (r >= 0 and c < ncol):
  6.         if tar == arr[r][c]:
  7.             return (r + 1, c + 1)
  8.         elif tar > arr[r][c]:
  9.             c += 1
  10.         else:
  11.             r -= 1
  12.     return None
  13.  
  14.  
  15. def find2(arr, tar):
  16.     nrow = len(arr)
  17.     ncol = len(arr[0])
  18.     r, c = 0, ncol - 1
  19.     while (r < nrow and c >= 0):
  20.         if tar == arr[r][c]:
  21.             return (r + 1, c + 1)
  22.         elif tar > arr[r][c]:
  23.             r += 1
  24.         else:
  25.             c -= 1
  26.     return None
  27.  
  28.  
  29. int_str = """
  30. 1 4 7 11 15
  31. 2 5 8 12 19
  32. 3 6 9 16 22
  33. 10 13 14 17 24
  34. 18 21 23 26 30
  35. """
  36.  
  37. int_arr = [list(map(int, line.split())) for line in int_str.strip().split('\n')]
  38. print(find1(int_arr, 1), find2(int_arr, 1))
  39. print(find1(int_arr, 12), find2(int_arr, 12))
  40. print(find1(int_arr, 9), find2(int_arr, 9))
  41. print(find1(int_arr, 100), find2(int_arr, 100))
Add Comment
Please, Sign In to add comment