01_trebuchet.py 526 B

1234567891011121314151617
  1. #!/usr/bin/env python3
  2. import sys
  3. import re
  4. WORDS = r'\d one two three four five six seven eight nine'.split()
  5. def digit(d):
  6. return int(d) if d.isdigit() else WORDS.index(d)
  7. def calibrate(line, pattern):
  8. first = re.search(pattern, line)
  9. last = re.match('.*(%s)' % pattern, line[first.end():])
  10. return digit(first[0]) * 10 + digit(last[1] if last else first[0])
  11. lines = sys.stdin.readlines()
  12. print(sum(calibrate(line, r'\d') for line in lines))
  13. print(sum(calibrate(line, '|'.join(WORDS)) for line in lines))