May 27, 2010

Parsing string

Yesterday I was checking my marks from C++ Programming subject (as it turned out, there's almost no chance I will pass it :/). Points from each lab are stored in spreadsheet, and when copied they looked like this :

"1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"

Because exams are closing, I'm starting to get lazy. That's why instead of copying and summing all the values in google, I thought about using Python to parse through this string to get their sum. That's what I came up with :
#note using fsum to preserve float loss
fsum(float(n) for n in str.replace(',','.').split())
And here's second solution, since ',' is a legitimate decimal point for many people.
import locale
locale.setlocale(0,"po")
sum(map(locale.atof, s.split()))

No comments:

Post a Comment