Skip to content
Related Articles
Open in App
Not now

Related Articles

Find the average of an unknown number of inputs in Python

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 Mar, 2023
Improve Article
Save Article

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-keyworded, 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




# function that takes arbitrary
# number of inputs
def avgfun(*n):
    sums = 0
 
    for t in n:
        sums = sums + t
 
    avg = sums / len(n)
    return avg
     
 
# Driver Code
result1 = avgfun(1, 2, 3)
result2 = avgfun(2, 6, 4, 8)
 
# Printing average of the list
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




# function that takes arbitrary
# number of inputs
 
 
def avgfun(*n):
    return sum(n) / len(n)
 
 
# Driver Code
result1 = avgfun(1, 2, 3)
result2 = avgfun(2, 6, 4, 8)
 
# Printing average of the list
print(round(result1, 2))
print(round(result2, 2))

Output

2.0
5.0

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))

Output

2.0
5.0

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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!