Given lists in a list, the task is to write a Python program to find the maximum product of elements of list in a Python 2D list.
Examples:
Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output : 504
Explanation:1*2*3 = 6, 4*5*6 = 120, 7*8*9 = 504
Since maximum is 504.
Input : [[3, 4], [1, 2, 3], [0, 0]]
Output : 12
Explanation:3*4 = 12, 1*2*3 = 6, 0*0 = 0
Since maximum is 12.
Using nested for-loops to get Maximum product of elements of list in a 2D list
We can traverse the Python 2-D list and multiply all the elements in a given list and by max() function get the maximum of product of all elements in lists of list.
Python3
# Python program to find Maximum product # of elements of list in a list of lists def prod(lis): maxi = 0 # traversal in the lists for x in lis: p = 1 # traversal in list of lists for i in x: p * = i maxi = max (p, maxi) return maxi # driver code l = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] print (prod(l)) |
Output:
504
Time Complexity: O(n*n)
Auxiliary Space: O(1)
Using List-Comprehension in Python to computer maximum product value
Iterate on the outer list using list comprehension and use prod() function to calculate each product of the inner list and pass the result to the max() function to find the maximum product value.
Python3
# function to calculate product # of a list of elements def prod(ll): z = 1 for i in ll: z * = i return z # driver code l = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] max_prod = max ([prod(inner_list) for inner_list in l]) print (max_prod) |
Output:
504
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Maximum product of elements of list Using functools.reduce() and itertools.mul
Python3
# function to calculate product # of a list of elements l = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] from functools import reduce import operator res = [] for i in l: res.append( reduce (operator.mul,i, 1 )) max_prod = max (res) print (max_prod) |
504
Time Complexity : O(n)
Auxiliary Space : O(n)