Aaron Toponce wrote:
> He probably forgot. He's a Java guy now. We haven't seen that solution
> yet, have we?
To nudge myself to get in the habit of using doctests instead of older
testing methods, I went ahead and wrote the doctest version. I suspect
it looks odd to people not familiar with the pattern, but a lot of
Python programmers strongly prefer this.
Shane
import re
def secondize(expr):
"""Evaluate an expression containing H:M:S values.
>>> secondize('8:12')
492.0
>>> secondize('10:12:33')
36753.0
>>> secondize('5 + 3*6:50')
1235.0
>>> secondize('8 / 13*15:32:20.4 - 10')
-10.0
>>> secondize('10:25 - 6:50 / 12:23:44') - (625.0 - 410.0 / 44624.0)
0.0
"""
def replace(match):
h, m, s = match.groups()[1:]
return str(int(h or 0) * 3600 + int(m) * 60 + float(s))
return eval(re.sub(r"((\d+):)?(\d+):([\d.]+)", replace, expr))
if __name__ == '__main__':
import doctest
doctest.testmod()
/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/