SHARE
TWEET

matrixsearch

phillip1882 Feb 10th, 2012 103 Never
  1. def search(matrix,value):
  2.    sizex = len(matrix[0])-1
  3.    sizey = len(matrix)-1
  4.    initialx = sizex
  5.    initialy = 0
  6.    while initialx >= 0 and initialy <= sizey:
  7.       if matrix[initialy][initialx] == value:
  8.          return initialx,initialy
  9.       elif  matrix[initialy][initialx] > value:
  10.          initialx -= 1
  11.       elif matrix[initialy][initialx] <= value:
  12.          initialy += 1
  13.       else:
  14.          return -1,-1
  15.    return -1,-1
  16.  
  17. M = [ [  1,  5,  7,  9 ],  
  18.     [  4,  6, 10, 15 ],  
  19.     [  8, 11, 12, 19 ],  
  20.     [ 14, 16, 18, 21 ] ]  
  21. value = 12
  22. print(search(M,value))
  23. value = 17
  24. print(search(M,value))
RAW Paste Data
Top