While working with Python, we can have a problem in which we need to find geometric mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formula The simpler manner to approach this problem is to employ the formula for finding geometric mean and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of # Geometric Mean of List # using loop + formula import math
# initialize list test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
# printing original list print ( "The original list is : " + str (test_list))
# Geometric Mean of List # using loop + formula temp = 1
for i in range ( 0 , len (test_list)) :
temp = temp * test_list[i]
temp2 = ( float )(math. pow (temp, ( 1 / len (test_list))))
res = ( float )(temp2)
# printing result print ( "The geometric mean of list is : " + str (res))
|
The original list is : [6, 7, 3, 9, 10, 15] The geometric mean of list is : 7.443617568993922
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the loop + formula which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re using constant additional space
Method #2 : Using statistics.geometric_mean() This task can also be performed using inbuilt function of geometric_mean(). This is new in Python versions >= 3.8.
# Python3 code to demonstrate working of # Geometric Mean of List # using statistics.geometric_mean() import statistics
# initialize list test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
# printing original list print ( "The original list is : " + str (test_list))
# Geometric Mean of List # using statistics.geometric_mean() res = statistics.geometric_mean(test_list, 1 )
# printing result print ( "The geometric mean of list is : " + str (res))
|
The original list is : [6, 7, 3, 9, 10, 15] The geometric mean of list is : 7.443617568993922
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #3: Using numpy library
Note: Install numpy module using command “pip install numpy”
We can use the numpy library which has a numpy.prod() function to find the product of all elements in the list and then use numpy.power() function with the reciprocal of the length of the list as the exponent to find the geometric mean.
import numpy as np
# initialize list test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
# printing original list print ( "The original list is : " + str (test_list))
# Geometric Mean of List using numpy result = np.power(np.prod(test_list), 1 / len (test_list))
# printing result print ( "The geometric mean of list is : " + str (result))
#This code is contributed by Edula Vinay Kumar Reddy |
Output:
The original list is : [6, 7, 3, 9, 10, 15]
The geometric mean of list is : 7.443617568993922
Time complexity: O(n)
Auxiliary space: O(1)