My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update solution for 2018/04

+19 -33
+16 -31
2018/day04.py
··· 1 1 import fileinput 2 2 from collections import Counter, defaultdict 3 3 4 - from utils import parse_line 4 + from utils import parse_nums 5 5 6 6 7 7 # Read problem input 8 - EVENTS = [] 9 - for line in fileinput.input(): 10 - data = parse_line(r'\[(\d+)-(\d+)-(\d+) (\d+):(\d+)\] (.+)', line) 11 - EVENTS.append(data) 12 - 13 - EVENTS.sort() 8 + EVENTS = sorted(parse_nums(line, negatives=False) for line in fileinput.input()) 14 9 15 10 # Process events 16 11 SHIFTS = Counter() 17 12 GUARDS = defaultdict(Counter) 18 13 curr_id = None 19 - sleep = None 14 + sleep_min = None 20 15 21 - for year, month, date, hour, minute, action in EVENTS: 22 - if 'begins' in action: 23 - curr_id = int(action.split()[1][1:]) 16 + for record in EVENTS: 17 + if len(record) == 6: # shift begins 18 + curr_id = int(record[-1]) 24 19 25 - elif 'asleep' in action: 26 - sleep = hour, minute 20 + elif sleep_min is None: # falls asleep 21 + sleep_min = record[-1] 27 22 28 - elif 'wakes' in action: 29 - h, m = sleep 30 - SHIFTS[curr_id] += ((hour - h) % 24) * 60 + (minute - m) 31 - sleep = None 23 + else: # wakes up 24 + minute = record[-1] 25 + SHIFTS[curr_id] += minute - sleep_min 26 + for m in range(sleep_min, minute): 27 + GUARDS[curr_id][m] += 1 32 28 33 - for x in range(h * 60 + m, hour * 60 + minute): 34 - GUARDS[curr_id][x % 60] += 1 29 + sleep_min = None 35 30 36 31 # Compute Part 1 answer 37 32 guard_id = SHIFTS.most_common(1)[0][0] ··· 39 34 print "Strategy 1 checksum:", guard_id * minute 40 35 41 36 # Compute Part 2 answer 42 - max_cnt = 0 43 - max_min = 0 44 - max_id = 0 45 - 46 - for guard_id, minutes in GUARDS.items(): 47 - minute, count = minutes.most_common(1)[0] 48 - if count > max_cnt: 49 - max_cnt = count 50 - max_min = minute 51 - max_id = guard_id 52 - 53 - print "Strategy 2 checksum:", max_id * max_min 37 + guard_id, (minute, _) = max(((i, c.most_common(1)[0]) for i, c in GUARDS.items()), key=lambda x: x[1][1]) 38 + print "Strategy 2 checksum:", guard_id * minute
+3 -2
2018/utils.py
··· 21 21 return ret 22 22 23 23 24 - def parse_nums(line): 25 - return [int(n) for n in re.findall(r'-?\d+', line)] 24 + def parse_nums(line, negatives=True): 25 + num_re = r'-?\d+' if negatives else r'\d+' 26 + return [int(n) for n in re.findall(num_re, line)] 26 27 27 28 28 29 def new_table(val, width, height):