zinterval.py 1002 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import re
  2. multipliers = {
  3. 's': 1,
  4. 'm': 60,
  5. 'h': 60*60,
  6. 'd': 24*60*60,
  7. 'w': 7*24*60*60,
  8. 'y': 365*24*60*60
  9. }
  10. def parse(s):
  11. secs = 0.0
  12. items = re.split(r'\s', s)
  13. for item in items:
  14. match = re.match('^(?P<amount>[0-9]+)(?P<unit>.*)$', item)
  15. if not match:
  16. continue # ignore
  17. unit = match.group('unit').lower()
  18. if unit not in multipliers:
  19. continue # ignore
  20. multiplier = multipliers[unit]
  21. secs += float(match.group('amount')) * multiplier
  22. return secs
  23. testcases = [
  24. ( '10s', 10),
  25. ('1m 1s', 61),
  26. ('20m 20s', 1220),
  27. ('1w 3d 2h 4m 5s', 10*24*60*60+7200+240+5),
  28. ('1W 3D 2H 4M 5S', 10*24*60*60+7200+240+5),
  29. ('', 0),
  30. (' ', 0),
  31. (' 1m 3s ', 63)
  32. ]
  33. if __name__ == '__main__':
  34. for input, output in testcases:
  35. real = parse(input)
  36. if real != output:
  37. print "%r gives %r, not %r" % (input, real, output)
  38. print 'done'