Monday, May 4, 2009

Sum and average calculation using python


Input file:

$ cat data.txt
12313.23
4005.12
13434.12
2133.21
213123.21
9000.23


Required: Calculate simple sum and average of the above float values.
Python script:

data = open("data.txt").read().split()
s = sum([ float(i) for i in data ])
print "Sum=" , s
print "Avg=" , s/len(data)

Executing it:

$ python sum-avg.py
Sum= 254009.12
Avg= 42334.8533333


Awk solution for the same:

$ awk '
{s+=$0}
END {printf "Sum =%10.2f,Avg = %10.2f\n",s,s/NR}
' data.txt

Output:

Sum = 254009.12,Avg = 42334.85


Related functions and concepts:
a) Python for loop read here
b) The built-in function len() returns the length of a string
c) python numeric types read here

0 Comments: