Calculate the average of a number’s digits in Python

In this Python tutorial, we shall be seeing how to calculate the average of the digits of a number.

What exactly does this mean?

Consider the number 537. The average of its digits would be the sum of its digits divided by the number of digits.

Therefore, the average of the digits of 537 is

(5+3+7)/3 = 15/3 = 5.0

Steps:

  1. Design a function to calculate the number of digits in a number.
  2. Design a function to calculate the sum of the digits of a number.
  3. Calculate the average of digits of a number by dividing the sum and the number of digits in a function.

Let us now proceed to the Python code and its output.

Python program to Calculate the average of a number’s digits

Code in Python:-

#Function to calculate the number of digits in a number
def digCount(num):
c = 0
while num != 0:
num = num//10
c += 1
return c
#Function to calculate the sum of digits of a number
def digSum(num):
temp = num
sum = 0
for i in range(digCount(num)):
sum+=num%10
num//=10
return sum
#Function to calculate the average of digits of a number
def calcAvg(num):
return (digSum(num)/digCount(num))
#Initialising a list of numbers whose digits we shall average 
numbers = [123,723,263,436,912]
#Initialising an empty list where we shall append the averages
avg_dig = []
#Iterating over the list and using precision handling to store till 2 digits after the decimal places of the average
for i in numbers:
avg_dig.append('%.2f'%calcAvg(i))
#Printing the list containing the original numbers
print('Original Numbers::')
print(numbers)
#Printing the list containing the averages
print('Average of digits::')
print(avg_dig)

Output:-

Original Numbers::
[123, 723, 263, 436, 912]
Average of digits::
['2.00', '4.00', '3.67', '4.33', '4.00']

–> digCount() function:-

  • Initialise a counter ‘c’ as 0.
  • Keep floor dividing the number till the number reaches 0 and increment the counter at each step.
  • Return the counter.

–> digSum() function:-

  • Store the value of the argument in a temporary variable.
  • Initialise a variable ‘sum’ as 0.
  • Extract each digit from the number and add it to the variable sum.
  • Floor divide the number to remove the last digit.
  • Return the sum

–> calcAvg() function:-

  • Return the division of the sum of digits and the number of digits of the argument passed.

 

Iterate over the list ‘numbers’ and store the average of its digits in the list ‘avg_dig’.

Print both lists separately.

I hope this Python tutorial was useful!

Also read: Taking a number and rearranging its digits in ascending order to form a new number in Python

Leave a Reply

Your email address will not be published.