-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcalc
executable file
·77 lines (62 loc) · 2.17 KB
/
tcalc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
# encoding: utf-8 (as per PEP 263)
import sys
import re
def timetomin(t):
parts = t.split(':')
return 60*int(parts[0]) + int(parts[1])
def mintotime(m):
return '%01d:%02d' % (m//60, m%60)
def timediff(t1, t2):
t1 = timetomin(t1)
t2 = timetomin(t2)
if t2 > t1:
# same day
d = t2 - t1
else:
# past midnight
d = (24*60 - t1) + t2
return d
def main():
line = sys.stdin.readline().strip()
while line:
verbose = line.endswith('?')
tokens = re.findall('\d{1,2}:\d{2}|\d{1,2}|\.+|-|\+', line)
dots = [i for i, x in enumerate(tokens) if '.' in str(x)]
for i in dots:
tokens[i] = timediff(tokens[i-1], tokens[i+1])
if verbose:
print('. %s to %s = %d minutes (%s)' % (tokens[i-1], tokens[i+1], tokens[i], mintotime(tokens[i])))
tokens[i-1] = None
tokens[i+1] = None
tokens = [x for x in tokens if x is not None]
composites = [i for i, x in enumerate(tokens) if ':' in str(x)]
for i in composites:
t = timetomin(tokens[i])
if verbose:
print('> %s = %d minutes (%s)' % (tokens[i], t, mintotime(t)))
tokens[i] = t
sum = 0
while tokens:
if tokens[0] not in ['-', '+']:
tokens[0] = int(tokens[0])
sum += tokens[0]
if verbose:
print('< %d minutes = %d total (%s)' % (tokens[0], sum, mintotime(sum)))
elif tokens[0] == '-':
tokens[1] = int(tokens[1])
sum -= tokens[1]
if verbose:
print('- %d minutes = %d total (%s)' % (tokens[1], sum, mintotime(sum)))
del tokens[1]
elif tokens[0] == '+':
tokens[1] = int(tokens[1])
sum += tokens[1]
if verbose:
print('+ %d minutes = %d total (%s)' % (tokens[1], sum, mintotime(sum)))
del tokens[1]
del tokens[0]
print(mintotime(sum))
line = sys.stdin.readline().strip()
if __name__ == '__main__':
main()