Reputation: 181
When prompted for a number of rows in a matrix, then prompted to enter the elements of those rows, I need to find the largest element in that matrix and return its location (row and column).
For example, if I enter 2 rows as follows:
[1 3 7] [4 8 1]
the location of the largest element would be (1, 1) meaning row index 1 and column index 1.
I have the following code, which semi works to get the location:
def main():
matrix = []
numRows = eval(input("Enter the number of rows in the list: "))
for i in range(numRows):
rows = input("Enter a row: ")
items = rows.split()
list = [eval(x) for x in items]
matrix.append(list)
return locateLargest(matrix)
def locateLargest(a):
for i in range(len(a)):
indexOfMaxRow = 0
maxRow = max(a[i])
for row in range(len(a)):
if max(a[row]) > maxRow:
maxRow = max(a[row])
indexOfMaxRow = row
for j in range(len(a)):
indexOfMaxColumn = 0
maxColumn = max(a[j])
for column in range(len(a)):
if max(a[column]) > maxColumn:
maxColumn = max(a[column])
indexOfMaxColumn = column
print("The location of the largest element is at (", indexOfMaxRow, ", ", indexOfMaxColumn, ")")
main()
I think my code is wrong under def locateLargest(a)
since everything works until the results are printed. Can anyone advise what is wrong with it? Thanks in advance for any input!
Upvotes: 3
Views: 7568
Reputation: 74645
That is overly complex:
A = [[1, 3, 7],
[4, 8, 1]]
def max_element(A):
r, (c, l) = max(map(lambda t: (t[0], max(enumerate(t[1]), key=lambda v: v[1])), enumerate(A)), key=lambda v: v[1][1])
return (l, r, c)
print max_element(A)
Prints
(8, 1, 1)
Upvotes: 2
Reputation: 238081
If you can use numpy, then the indices of maximum value in an array can be easily found:
import numpy as np
na = np.array(a)
indices = np.where(na == na.max())
Upvotes: 6
Reputation: 59571
Your locateLargest
function can be much simpler:
def locateLargest(matrix):
largest_num = None
row = None
col = None
for row_idx, row in enumerate(matrix):
for col_idx, num in enumerate(row):
if num > largest_num or largest_num is None:
largest_num = num
row = row_idx
col = col_idx
return (largest_num, row, col)
This function returns the largest number, as well as the column and row index (0 based index).
Example:
>>> print(locateLargest([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
(9, 2, 2)
Upvotes: 1