Python | Row lengths in Matrix

The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using max() + map() + sum() + list comprehension

The combination of above functions can help to get the solution to this particular problem in just a one line and hence quite useful. The sum function computes the sum of sublists, max function can be used to order in descending and all this bound together using list comprehension.

 # Python3 code to demonstrate # Row lengths in matrix # using max() + map() + sum() + list comprehension    # initializing list test_list = [[4, 5, 6], [7, 8], ]    # printing original list print("The original list : " + str(test_list))    # using max() + map() + sum() + list comprehension # Row lengths in matrix res = [sum(len(row) > idx for row in test_list)     for idx in range(max(map(len, test_list)))]    # print result print("The row lengths in matrix : " + str(res))

Output :

The original list : [[4, 5, 6], [7, 8], ]
The row lengths in matrix : [3, 2, 1]

Method #2 : Using sum() + filter() + zip_longest()

This problem can also be solved using the set of functions above. The filter function can be used to get the separate lists and the task of binding for summation done by sum function is performed by zip_longest function.

 # Python3 code to demonstrate # Row lengths in matrix # using sum() + filter() + zip_longest() from itertools import zip_longest    # initializing list test_list = [[4, 5, 6], [7, 8], ]    # printing original list print("The original list : " + str(test_list))    # using sum() + filter() + zip_longest() # Row lengths in matrix res = [sum(1 for idx in filter(None.__ne__, i))               for i in zip_longest(*test_list)]    # print result print("The row lengths in matrix : " + str(res))

Output :

The original list : [[4, 5, 6], [7, 8], ]
The row lengths in matrix : [3, 2, 1]

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.