Last active
February 1, 2019 22:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am looking for another approach.