![]() |
VOOZH | about |
Given a dictionary, find the mean of all the values present.
Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4}
Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15}
Output : 10.0
Explanation : Mean of these is 10.0This is a brute way in which this task can be performed. In this, we loop through each value and perform summation and then the result is divided by total keys extracted using len().
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(1) constant additional space required
The combination of above functions can be used to solve this problem. In this, we perform summation using sum() and size() of total keys computed using len().
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7Using reduce function to calculate the sum of values and then dividing by the length of the dictionary
Approach:
Mean: 7.0
Time complexity: O(n)
Space complexity: O(1)
Approach:
Output
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0
Time complexity:
Converting dictionary values to a NumPy array takes O(n) time, where n is the number of values in the dictionary.
Computing the mean using the NumPy mean() function takes O(1) time.
Therefore, the overall time complexity is O(n).
Auxiliary space complexity:
Converting dictionary values to a NumPy array requires O(n) auxiliary space.
Computing the mean using the NumPy mean() function requires O(1) auxiliary space.
Therefore, the overall auxiliary space complexity is O(n).