Find Average of a Number Digits in Python
AIn this article, we will see how to find the average of the digits of a number in Python.
Examples:
Input: N = 642 Output: 4.0 Explanation: (6+4+2)/3 = 12/3 = 4.0 Input: N = 3504 Output: 3.0 Explanation: (3+5+0+4)/4 = 12/4 = 3.0
Calculate the average of a number of digits in python if the number is an integer:
Follow the below steps to solve the problem:
- Loop over the digits of the number.
- Count the total number of digits of the number
- Calculate the sum of all the digits of the number
- Calculate and return the number digit average
Following is an implementation of the above approach:
Python3
# Python function to find the # average of all the digits of a number def digitAverage(n): digiSum, digiLen = 0 , 0 # loop over the digits of the number while n: # calculating the number of all the digits digiLen + = 1 # calculating the sum of all the digits digiSum + = n % 10 # remove the last digit from the original number # to continue to loop over the digits n = n / / 10 # calculate and return the average return (digiSum / digiLen) print (digitAverage( 642 )) print (digitAverage( 3504 )) |
Output
4.0 3.0
Time complexity: O(n)
Auxiliary Space: O(1)
Calculate the average of a number of digits in python if the number is a floating-point number:
In case the input number is a floating point number, we will first convert it into an integer by shifting all the decimal digits by repeatedly multiplying it by 10.
To check if a float is equivalent to an integer we can use the is_integer() method of the float class.
Follow the below steps to solve the problem:
- First, we will repeatedly multiply the decimal number by 10 until it becomes an integer
- Then we can simply follow our previous approach
- Loop over the digits of the number.
- Count the total number of digits of the number
- Calculate the sum of all the digits of the number
- Calculate and return the number digit average
Following is an implementation of the above approach:
Python3
# Python function to find the average # of all the digits of a number def digitAverage(n): # changing the float into an integer # by repeatedly multiplying the number by 10 n = float (n) while not n.is_integer(): n * = 10 digiSum, digiLen = 0 , 0 # loop over the digits of the number while n: # calculating the number of all the digits digiLen + = 1 # calculating the sum of all the digits digiSum + = n % 10 # remove the last digit from the original number # to continue to loop over the digits n = n / / 10 # calculate and return the average return (digiSum / digiLen) print (digitAverage( 642.0 )) print (digitAverage( 350.4 )) |
Output
4.0 3.0
Time complexity: O(d), d is the number of digits in the given number n.
Auxiliary space: O(1).