I want to see the position of the maximum element in each row.
Input:
arr = [[3, 4, 1, 8],
[1, 4, 9, 11],
[76, 34, 21, 1],
[2, 1, 4, 5]]
Output:
[3, 3, 0, 3]
I have already implemented this function, but I don’t know why it’s not working. Please help me.
# Python program to find maximum
# element of each row in a matrix
# importing numpy
import numpy
# Function to get max element
def maxelement(arr):
listmax = []
# get number of rows and columns
no_of_rows = len(arr)
no_of_column = len(arr[0])
for i in range(no_of_rows):
# Initialize max1 to 0 at beginning
# of finding max element of each row
max1 = 0
for j in range(no_of_column):
if arr[i][j] > max1 :
max1 = arr[i][j]
# print maximum element of each row
listmax.append(max1)
return(listmax)
>Solution :
Instead of appending the maximum value (max1) you want to append the index of the maximum:
# Python program to find maximum
# element of each row in a matrix
# importing numpy
import numpy
# Function to get max element
def maxelement(arr):
listmax = []
# get number of rows and columns
no_of_rows = len(arr)
no_of_column = len(arr[0])
for i in range(no_of_rows):
# Initialize max1 to 0 at beginning
# of finding max element of each row
max1 = 0
max_index = 0
for j in range(no_of_column):
if arr[i][j] > max1 :
max1 = arr[i][j]
max_index = j
# print maximum index of each row
listmax.append(max_index)
return(listmax)