Python – Ways to find Geometric Mean in List
Last Updated :
09 Apr, 2023
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
import math
test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
print ( "The original list is : " + str (test_list))
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)
print ( "The geometric mean of list is : " + str (res))
|
Output :
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
import statistics
test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
print ( "The original list is : " + str (test_list))
res = statistics.geometric_mean(test_list, 1 )
print ( "The geometric mean of list is : " + str (res))
|
Output :
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.
Python
import numpy as np
test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]
print ( "The original list is : " + str (test_list))
result = np.power(np.prod(test_list), 1 / len (test_list))
print ( "The geometric mean of list is : " + str (result))
|
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)
Share your thoughts in the comments
Please Login to comment...