Find Average of a Number Digits in Python
Last Updated :
07 Feb, 2023
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
def digitAverage(n):
digiSum, digiLen = 0 , 0
while n:
digiLen + = 1
digiSum + = n % 10
n = n / / 10
return (digiSum / digiLen)
print (digitAverage( 642 ))
print (digitAverage( 3504 ))
|
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
def digitAverage(n):
n = float (n)
while not n.is_integer():
n * = 10
digiSum, digiLen = 0 , 0
while n:
digiLen + = 1
digiSum + = n % 10
n = n / / 10
return (digiSum / digiLen)
print (digitAverage( 642.0 ))
print (digitAverage( 350.4 ))
|
Time complexity: O(d), d is the number of digits in the given number n.
Auxiliary space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...