re: AoC Day 4: Repose Record VIEW POST

FULL DISCUSSION
 

Had a particularly long day at work, so got to the problem late and only just now finished. I'm with all of you that this one was less fun...I haven't refactored since I don't have much brain left for today, but here's my solution for now!

#!/usr/bin/env python

import operator
import re
from collections import defaultdict

RECORD_PATTERN = re.compile('\[.* \d\d:(\d\d)\] .*')
GUARD_ID_PATTERN = re.compile('.* Guard #(\d+) begins shift')


if __name__ == '__main__':
    with open('input.txt') as guard_records_file:
        guard_records = guard_records_file.read().splitlines()
        guard_records.sort()

    minute_data = defaultdict(lambda: defaultdict(int))
    guard_data = defaultdict(lambda: defaultdict(int))

    for guard_record in guard_records:
        minute = int(RECORD_PATTERN.match(guard_record).group(1))

        if 'begins shift' in guard_record:
            just_started_shift = True
            current_guard = int(GUARD_ID_PATTERN.match(guard_record).group(1))
        elif 'wakes up' in guard_record:
            minutes_asleep = minute - fell_asleep_minute
            for sleep_minute in range(fell_asleep_minute, minute):
                guard_data[current_guard][sleep_minute] += 1
                minute_data[sleep_minute][current_guard] += 1
        elif 'falls asleep' in guard_record:
            fell_asleep_minute = minute

    # Part 1
    guard_who_slept_most = max(guard_data, key=lambda key: sum(guard_data[key].values()))
    sleepiest_minute_for_guard = max(minute_data, key=lambda key: minute_data[key][guard_who_slept_most])
    print(guard_who_slept_most * sleepiest_minute_for_guard)

    # Part 2
    guard_with_sleepiest_minute = max(guard_data, key=lambda key: max(guard_data[key].values()))
    sleepiest_minute_for_guard = max(guard_data[guard_with_sleepiest_minute], key=lambda key: guard_data[guard_with_sleepiest_minute][key])
    print(guard_with_sleepiest_minute * sleepiest_minute_for_guard)
code of conduct - report abuse