Calculate Statistics
You are given a list of
n
numbers and your task is to implement a function calculate_statistics
that will calculate and return specific statistical measures: the mean, median, and mode.The function should take one positional argument
numbers
, which is the list of numbers, and three keyword-only arguments: mean
, median
, and mode
, each with a default value of False
. The function should calculate and return only the statistical measures that are set to True
. If no statistical measures are requested (all set to False
), the function should return an empty dictionary.The output of the function should be a dictionary with the names of the statistical measures as keys and the calculated values as the values. The function should be defined as follows:
def calculate_statistics(numbers, *, mean=False, median=False, mode=False):
Input | Output |
calculate_statistics([4, 8, 6, 5, 3, 2, 8, 9, 2], mean=True) | {'mean': 5.222222222222222} |
calculate_statistics([4, 8, 6, 5, 3, 2, 8, 9, 2], median=True) | {'median': 5} |
calculate_statistics([4, 8, 6, 5, 3, 2, 8, 9, 2], mode=True) | {'mode': [2, 8]} |
calculate_statistics([4, 8, 6, 5, 3, 2, 8, 9, 2], mean=True, median=True, mode=True) | {'mean': 5.222222222222222, 'median': 5, 'mode': [2, 8]} |
calculate_statistics([4, 8, 6, 5, 3, 2, 8, 9, 2]) | {} |
calculate_statistics([1, 2], median=True, mean=True, mode=True) | {'mean': 1.5, 'median': 1.5, 'mode': [1, 2]} |
Note: In the case of a multi-modal data set, the function should return all modes in a list, ordered from smallest to largest. If the data set is not multi-modal, the function should return the single mode in a list. If there is no mode, the function should return an empty list as the value for 'mode'.
mean
The mean of a list of numbers is the sum of all the numbers divided by the number of numbers.
median
The median is the middle value when a data set is ordered from least to greatest.
mode
The mode is the number that appears most frequently in a data set.
A data set may have one mode, more than one mode, or no mode at all.
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB