I am trying to write a function that will take a target number, and a matrix as its parameter, and will return the 'co-ordinates' of the target number. If the target number doesn't exist, (-1, -1) will be returned.
It is assumed there will only be one occurrence of the target number.
Example matrix:
my_matrix = [
[1, 4, 7, 12, 15, 1000],
[2, 5, 19, 31, 32, 1001],
[3, 8, 24, 33, 35, 1002],
[40, 41, 42, 44, 45, 1003],
[99, 100, 103, 106, 128, 1004]
]
example input/output:
target_number = 19 output = (1, 2)
Firstly I wrote the function to our put the indices of the col/row position:
def find_target(target, matrix):
for i, row in enumerate(matrix):
for j, col in enumerate(row):
if col == target:
return i, j
This will output 'None' is the number doesn't exists, so I then tried to implement if/else, then tried try/except to outout (-1, -1) if the number doesn't exists however my attempts at implementing this seem to override the above, and output (-1, -1) even if the number exists.
My attempts:
def find_target(target, matrix):
for i, row in enumerate(matrix):
for j, col in enumerate(row):
try:
if col == target:
return i, j
else:
raise ValueError
except ValueError:
return -1, -1
def find_target(target, matrix):
for i, row in enumerate(matrix):
for j, col in enumerate(row):
if col == target:
return i, j
else:
return -1, -1
def find_target(target, matrix):
try:
for i, row in enumerate(matrix):
for j, col in enumerate(row):
if col == target:
return i, j
except:
return -1, -1
None of the above seem to give the desired output, they will either output(-1, -1) regardless of input, or will output 'None' if the number doesn't exist. I'm going to keep trying to understand why this is ongoing, but any pointers would be appreciated.
Also, please note I am quite new to this; I appreciate feedback, and I always make a point of trying various methods/ implementations etc before coming here to ask! :)
Explanations about your failed attempts, in order:
The solution is much simpler: you want to return -1,-1 if nothing else is returned, thus after your loops end:
def find_target(target, matrix):
for i, row in enumerate(matrix):
for j, col in enumerate(row):
if col == target:
return i, j
return -1,-1