Programming challenge

Shane Hathaway shane at hathawaymix.org
Fri Sep 28 11:40:28 MDT 2007


Sasha Pachev wrote:
> Problem:
> 
> Given a string that could contain arithmetic expressions, with the
> addition that numeric constants could be potentially expressed as
> times, e.g 1:36 for 96 seconds, or 2:10:08 for 2 hours 10 minutes and
> 8 seconds, also decimal fractions after seconds are allowed, e.g
> 3:45.6 or 3:40:50.67, replace all the time values with their
> equivalent number of seconds.

Here's a Python solution with much plagiarism from Hans. ;-)

Shane


import re

def secondize(expr):
    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))

def test():
    tests = {
        '8:12': 492,
        '10:12:33': 36753,
        '5 + 3*6:50': 1235,
        '8 / 13*15:32:20.4 - 10': -10,
        '10:25 - 6:50 / 12:23:44': 625.0 - 410.0 / 44624.0,
    }
    for expr, expect in tests.items():
        if secondize(expr) == expect:
            print "%s == %s" % (expr, expect)
        else:
            print "error on", expr

if __name__ == '__main__':
    test()





More information about the PLUG mailing list