Find the average of an unknown number of inputs in Python
Prerequisites: *args and **kwargs in Python
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyword, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. In this article, the task is to find the average of the unknown number of inputs.
Input : 1, 2, 3 Output : 2.00 Input : 2, 6, 4, 8 Output: 5.00
Below is the implementation.
Time complexity: O(n), where n is the number of inputs passed to the function.
Auxiliary space: O(1), as the amount of memory used by the function does not increase with the size of the input.
Method 2: Use the built-in Python function sum() to calculate the sum of the inputs and then divide it by the length of the input to get the average.
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: Use the reduce() function from the functools module.
- Import the functools module.
- Define a function that takes two arguments, a and b, and returns their sum.
- Use the reduce() function to sum all the input numbers.
- Divide the sum by the length of the input to get the average.
- Return the average.
Below is the implementation of the above approach:
Time complexity: O(n), where n is the number of input numbers, because it loops through all the inputs once to calculate the sum.
Auxiliary space: O(1) auxiliary space because it only uses a constant amount of memory to store the sum and the average.
Method 4: Using mean() from statistics module in python where we need to pass the list as an argument which will give the average as an output for the given list.
- Import the statistics module.
- Use the mean() function to get average.
- Print the average.
Time complexity: O(n), where n is the number of input numbers.
Auxiliary space: O(1)
Please Login to comment...