user2287240
user2287240

Reputation: 33

Find the row and column with the min value in python?

There is a function in my program that does the split and float. Then pass the matrix to main program. Now I have a function to find the row and column with the minimum value. I am getting a list of all the values but not a row and column which has the min value.

def closest_pair(e):
    for row in range(len(e)):
       for col in range(0,len(row),1):
          minrow = min(e[row])
          mincol = min(e[col])
          return ([minrow], [mincol])

E is the square matrix that is passed to this function from main. Input is the txt file with value such as this:

2 1 7 7
1 2 7 7
2 5 6 7
5 6 8 9

The expected output should be (1, 1) or row 1 and column 1 which has the low value in matrix.

This helped me to find the min value of row and column however the output was to get the pair. Also for the first value which would be 0, 0 would not count thus if the value for (0, 0) is 0 then that doesn't count as being the min value. With that said, for instance if row 1 and column 1, value is [2,2] as pair and are the only minimum pair than the output would (1,1).

Upvotes: 1

Views: 4122

Answers (2)

bozdoz
bozdoz

Reputation: 12860

e is a list of lists, correct?

Therefore min(e[row]) and min(e[col]) will give you lists.

You can also iterate over lists easier with enumerate

for col, row in enumerate(e):
  minrow = min(row)
  mincol = min([row[col] for row in e]) # need to transpose to a new list
  return ([minrow], [mincol])

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121534

You need to find the minimum value per row, and only then can you determine what the coordinates are for the row with the minimum column:

result = min((min((v, c) for c, v in enumerate(row)), r) for r, row in enumerate(e))
return result[1], result[0][1]

This code uses enumerate() to annotate each value with the column index, finds the minimum per row, annotates each row minimum with the row number (again with enumerate) and finds the minimum row. The result is a nested tuple with ((value, column), row), which we unpack to return the row and column indices.

Demo:

>>> e = [[2, 1, 7, 7], [1, 2, 7, 7], [2, 5, 6, 7], [5, 6, 8, 9]]
>>> result = min((min((v, c) for c, v in enumerate(row)), r) for r, row in enumerate(e))
>>> result[0][1], result[1]
(0, 1)

So position e[0][1] is a minimum value in the matrix. If you wanted to include the exact value of that position as well, return:

return result[1], result[0][1], result[0][0]

Upvotes: 2

Related Questions