Find the average of k digits from the beginning and l digits from the end of the given number | implementation of the approach ; Function to return the count of digits in num ; Function to return the sum of first n digits of num ; Remove the unnecessary digits ; Function to return the sum of the last n digits of num ; If the average can 't be calculated without  using the same digit more than once ; Sum of the last l digits of n ; Sum of the first k digits of n ( totalDigits - k ) must be removed from the end of the number to get the remaining k digits from the beginning ; Return the average ; Driver code
from math import pow NEW_LINE def countDigits ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE num //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def sumFromStart ( num , n , rem ) : NEW_LINE INDENT num //= pow ( 10 , rem ) NEW_LINE sum = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumFromEnd ( num , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def getAverage ( n , k , l ) : NEW_LINE INDENT totalDigits = countDigits ( n ) NEW_LINE if ( totalDigits < ( k + l ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sum1 = sumFromEnd ( n , l ) NEW_LINE sum2 = sumFromStart ( n , k , totalDigits - k ) NEW_LINE return ( sum1 + sum2 ) / ( k + l ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 123456 NEW_LINE k = 2 NEW_LINE l = 3 NEW_LINE print ( getAverage ( n , k , l ) ) NEW_LINE DEDENT