Program for average of an array without running into overflow | Python3 program for the above approach ; Function to calculate average of an array using standard method ; Stores the sum of array ; Find the sum of the array ; Return the average ; Function to calculate average of an array using efficient method ; Store the average of the array ; Traverse the array arr [ ] ; Update avg ; Return avg ; Driver Code ; Input ; Function call
import sys NEW_LINE def average ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum // N * 1.0 - 1 NEW_LINE DEDENT def mean ( arr , N ) : NEW_LINE INDENT avg = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT avg += ( arr [ i ] - avg ) / ( i + 1 ) NEW_LINE DEDENT return round ( avg , 7 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2147483647 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( " Average ▁ by ▁ Standard ▁ method : ▁ " , " { : . 10f } " . format ( - 1.0 * average ( arr , N ) ) ) NEW_LINE print ( " Average ▁ by ▁ Efficient ▁ method : ▁ " , " { : . 10f } " . format ( mean ( arr , N ) ) ) NEW_LINE DEDENT