Skip to content

Instantly share code, notes, and snippets.

@Kyeongan
Last active February 1, 2019 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kyeongan/9421d736f874d0d95c95fe42d7c54f78 to your computer and use it in GitHub Desktop.
Save Kyeongan/9421d736f874d0d95c95fe42d7c54f78 to your computer and use it in GitHub Desktop.
Write a function to return True or False if the target value is in the 2d array.
# Write a function to return True or False if the target value is in the 2d array.
data = [
[1, 3, 5, 7, 9, 10],
[3, 4, 6, 9, 10, 13],
[6, 8, 10, 12, 14, 16],
[10, 12, 14, 16, 18, 20],
[22, 23, 24, 25, 26, 27]
]
target = 5
def check_target_value(row, target):
for val in row:
if val == target:
return True
return False
def search_matrix(data, target):
pos_row = len(data)-1
pos_col = len(data[0])-1
while (pos_row >= 0):
if data[pos_row][0] > target:
if data[pos_row][pos_col] >= target:
if check_target_value(data[pos_row], target):
return True
pos_row -= 1
return False
assert search_matrix(data, 0) == False
assert search_matrix(data, 2) == False
assert search_matrix(data, 5) == True
assert search_matrix(data, 10) == True
assert search_matrix(data, 14) == True
assert search_matrix(data, 27) == True
assert search_matrix(data, 30) == False
@Kyeongan
Copy link
Author

Kyeongan commented Feb 1, 2019

I am looking for another approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment