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.
Examples:
Input : 1, 2, 3
Output : 2.00
Input : 2, 6, 4, 8
Output: 5.00
Below is the implementation.
Python3
def avgfun( * n):
sums = 0
for t in n:
sums = sums + t
avg = sums / len (n)
return avg
result1 = avgfun( 1 , 2 , 3 )
result2 = avgfun( 2 , 6 , 4 , 8 )
print ( round (result1, 2 ))
print ( round (result2, 2 ))
|
Output:
2.0
5.0
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.
Python3
def avgfun( * n):
return sum (n) / len (n)
result1 = avgfun( 1 , 2 , 3 )
result2 = avgfun( 2 , 6 , 4 , 8 )
print ( round (result1, 2 ))
print ( round (result2, 2 ))
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: Use the reduce() function from the functools module.
Step-by-step approach:
- 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:
Python3
import functools
def avgfun( * n):
sum_of_inputs = functools. reduce ( lambda a, b: a + b, n)
avg = sum_of_inputs / len (n)
return avg
result1 = avgfun( 1 , 2 , 3 )
result2 = avgfun( 2 , 6 , 4 , 8 )
print ( round (result1, 2 ))
print ( round (result2, 2 ))
|
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.
Step-by-step approach:
- Import the statistics module.
- Use the mean() function to get average.
- Print the average.
Python3
import statistics
result1 = statistics.mean([ 1 , 2 , 3 ])
result2 = statistics.mean([ 2 , 6 , 4 , 8 ])
print (result1)
print (result2)
|
Time complexity: O(n), where n is the number of input numbers.
Auxiliary space: O(1)
Last Updated :
07 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...