Python map function to find the row with the maximum number of 1’s



In this tutorial, we are going to write a program which finds a row with a maximum number of 1's from a matrix using the map function.

Let's say we have the following matrix.

matrix = [ [0, 0, 1], [1, 1, 1], [1, 1, 0] ]

We can write a program in different ways. But, using map function, we will follow the below procedure.

  • Initialise the matrix.
  • Find the number of 1's in every row using map function. Store them in a list.
  • Print the max from the list.

Example

## initializing the matrix
matrix = [
   [0, 0, 1],
   [1, 1, 1],
   [1, 1, 0]
]
## function to find number of 1's in a row
def number_of_ones(row):
   count = 0
   for i in row:
      if i is 1:
         count += 1
   return count
## finding the number of 1's in every row
## map returns an object which we converted into a list 
ones_count = list(map(number_of_ones, matrix))
## printing the index of max number from the list 
print(ones_count.index(max(ones_count)))

Output

If you run the above program, you will get the following result.

1

If you have any doubts regarding the program, please do mention them in the comment section.


Advertisements