-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04.py
81 lines (76 loc) · 2.66 KB
/
04.py
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
78
79
80
81
from lib import *
input = read_input(2018, 4)
days = {}
for line in input.splitlines():
day, hour, minute, action = re.match("^\[(\d\d\d\d-\d\d-\d\d) (\d\d):(\d\d)\] (.*)$", line).groups()
day = date.fromisoformat(day)
hour, minute = int(hour), int(minute)
match = re.match(r"^Guard #(\d+) begins shift$", action)
if match:
guard = int(match.group(1))
if hour == 23:
day += timedelta(days=1)
days.setdefault(day, [None, [None for _ in range(60)]])[0] = guard
elif action == "wakes up":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = True
elif action == "falls asleep":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = False
else:
assert False
guards = {}
for day, (guard, logs) in days.items():
awake = True
for i in range(60):
if logs[i] is None:
logs[i] = awake
else:
awake = logs[i]
if not awake:
guards.setdefault(guard, [0, {}])[0] += 1
guards[guard][1][i] = guards[guard][1].get(i, 0) + 1
guard = max(guards, key=lambda g: guards[g][0])
print(guard * max(guards[guard][1], key=lambda d: guards[guard][1][d]))
days = {}
for line in input.splitlines():
day, hour, minute, action = re.match("^\[(\d\d\d\d-\d\d-\d\d) (\d\d):(\d\d)\] (.*)$", line).groups()
day = date.fromisoformat(day)
hour, minute = int(hour), int(minute)
match = re.match("^Guard #(\d+) begins shift$", action)
if match:
guard = int(match.group(1))
if hour == 23:
day += timedelta(days=1)
days.setdefault(day, [None, [None for _ in range(60)]])[0] = guard
elif action == "wakes up":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = True
elif action == "falls asleep":
assert hour == 0
assert 0 <= minute < 60
days.setdefault(day, [None, [None for _ in range(60)]])[1][minute] = False
else:
assert False
guards = {}
for day, (guard, logs) in days.items():
awake = True
for i in range(60):
if logs[i] is None:
logs[i] = awake
else:
awake = logs[i]
if not awake:
guards.setdefault(guard, [0, {}])[0] += 1
guards[guard][1][i] = guards[guard][1].get(i, 0) + 1
best_cnt = -1
out = None
for g in guards:
cnt, best_minute = max((guards[g][1].get(i, 0), i) for i in range(60))
if cnt > best_cnt:
best_cnt = cnt
out = best_minute * g
print(out)