Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@Kyeongan 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
You can’t perform that action at this time.