Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Product of Prefix in list

Improve Article
Save Article
  • Last Updated : 26 Jan, 2023
Improve Article
Save Article

Nowdays, especially in the field of competitive programming, the utility of computing prefix product is quite popular and features in many problems. Hence, having a one liner solution to it would possess a great help. Let’s discuss certain way in which this problem can be solved. 

Method : Using list comprehension + list slicing This problem can be solved using the combination of above two functions in which we use list comprehension to extend logic to each element and then later compute the product, slicing is used to get product till the particular index. 

Python3




# Python3 code to demonstrate
# Product of Prefix in list
# using list comprehension + list slicing
 
# compute prod
def prod(test_list):
    res = 1
    for ele in test_list:
        res = res * ele
    return res
     
# initializing list
test_list = [3, 4, 1, 7, 9, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + list slicing
# Product of Prefix in list
res = [prod(test_list[ : i + 1 ]) for i in range(len(test_list))]
 
# print result
print("The prefix prod list is : " + str(res))

Output : 

The original list : [3, 4, 1, 7, 9, 1]
The prefix prod list is : [3, 12, 12, 84, 756, 756]

Method : Using numpy

Note: Install numpy module using command “pip install numpy”

This problem can be solved by using numpy library which has the cumprod() function that can be used to calculate the cumulative product of elements in the list

Python3




# Python3 code to demonstrate
# Product of Prefix in list
# using numpy
import numpy as np
 
# initializing list
test_list = [3, 4, 1, 7, 9, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# using numpy
result = np.cumprod(test_list)
 
# print result
print("The prefix prod list is : " + str(result))
#This code is contributed by Edula Vinay Kumar Reddy

Output:

The original list : [3, 4, 1, 7, 9, 1]
The prefix prod list is : [  3  12  12  84 756 756]
 

The time complexity of this approach is O(n) and the auxiliary space is O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!