Clean up some python

This commit is contained in:
Luke Hubmayer-Werner 2022-12-05 20:42:34 +10:30
parent ae3f6655a9
commit 246bcd4150
3 changed files with 28 additions and 6 deletions

14
2022/day4-sets.py Normal file
View File

@ -0,0 +1,14 @@
from helpers import *
with open('input/4', 'r') as file:
sets_per_line = [
(set(range(min(n[0], n[1]), max(n[0], n[1])+1)),
set(range(min(n[2], n[3]), max(n[2], n[3])+1)))
for n in lines_to_numbers(file.readlines())
]
count = sum((set1 <= set2 or set1 >= set2) for (set1, set2) in sets_per_line)
print(f'Part 1: {count} elves have no unique work in their pairing') # Part 1
count = sum((len(set1 & set2) > 0) for (set1, set2) in sets_per_line)
print(f'Part 2: {count} elf pairs have overlapping work in their pairing') # Part 2

View File

@ -1,13 +1,10 @@
import re from helpers import *
numbers_pattern = re.compile(r'((?:(?<!\d)-)?\d+)')
with open('input/5', 'r') as file: with open('input/5', 'r') as file:
input_stacks, _, input_orders = file.read().strip().partition('\n\n') input_stacks, _, input_orders = file.read().strip().partition('\n\n')
input_stacks_split = input_stacks.split('\n') starting_stack_strings = {int(l[0]):l[1:] for l in transpose_array_of_strings(input_stacks.split('\n'), reverse_y=True, strip=' []') if len(l) > 0}
input_stacks_transposed = [''.join(l[i] for l in input_stacks_split[::-1]).strip(' []') for i in range(len(input_stacks_split[0]))] order_numbers = lines_to_numbers(input_orders.split('\n'))
starting_stack_strings = {int(l[0]):l[1:] for l in input_stacks_transposed if len(l) > 0}
order_numbers = [[int(x) for x in numbers_pattern.findall(line)] for line in input_orders.split('\n')]
stacks = {k:[c for c in v] for k,v in starting_stack_strings.items()} stacks = {k:[c for c in v] for k,v in starting_stack_strings.items()}
for (num, source, dest) in order_numbers: for (num, source, dest) in order_numbers:

11
2022/helpers.py Normal file
View File

@ -0,0 +1,11 @@
import re
numbers_pattern = re.compile(r'((?:(?<!\d)-)?\d+)')
def line_to_numbers(line):
return [int(x) for x in numbers_pattern.findall(line)]
def lines_to_numbers(lines):
return [line_to_numbers(line) for line in lines]
def transpose_array_of_strings(aos, reverse_x = False, reverse_y = False, strip = ''):
return [''.join(l[i] for l in aos[::-1 if reverse_y else 1]).strip(strip) for i in range(len(aos[0]))[::-1 if reverse_x else 1]]