Python program using map function to find row with maximum number of 1's

ProgrammingPythonServer Side Programming

In this article, we will learn how to use map function to find row with maximum number of 1's. 2D array is given and the elements of the arrays are 0 and 1. All rows are sorted. We have to find row with maximum number of 1's. Here we use map (). The map function is the simplest one among Python built-ins used for functional programming. These tools apply functions to sequences and other iterables.

Let’s say the input is the following array −

[[0, 1, 1, 1, 1],[0, 0, 1, 1, 1],[1, 1, 1, 1, 1],[0, 0, 0, 0, 1]]

Output displays the row with maximum number of 1s −

2

Find row with maximum number of 1's

In this example, we will find a row with maximum number of 1’s using the map() function −

Example

def maximumFunc(n): max1 = list(map(sum,n)) print ("Row with maximum number of 1s = ",max1.index(max(max1))) # Driver program if __name__ == "__main__": n = [[0, 1, 0, 1, 1],[1, 0, 0, 0, 1],[1, 1, 1, 0, 1]] maximumFunc(n)

Output

Row with maximum number of 1s = 2

Find row with maximum number of 1's using for loop

In this example, we will find a row with maximum number of 1’s using a for loop simply −

Example

m = [[0, 1, 0, 1, 1],[1, 0, 1, 0, 1],[1, 0, 1, 0, 1]] mrows = len(m) max1 = 0 for k in range(mrows): c = m[k].count(1) if(c >= max1): max1 = c res = k+1 print("The row with maximum number of 1s = ", res)

Output

The row with maximum number of 1s = 3
raja
Updated on 11-Aug-2022 09:03:32

Advertisements