Python Program to get Maximum product of elements of list in a 2D list
Last Updated :
27 Jul, 2023
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
def prod(lis):
maxi = 0
for x in lis:
p = 1
for i in x:
p * = i
maxi = max (p, maxi)
return maxi
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
def prod(ll):
z = 1
for i in ll:
z * = i
return z
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
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)
|
Time Complexity : O(n)
Auxiliary Space : O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...