AoC #5 Input Parsing
unknown
python
2 years ago
1.0 kB
16
Indexable
import re
numre = re.compile(r"\d+")
# Deserialize input
seed_ranges: list[tuple] = []
mapping_sections: list[list] = []
with open("./input_5.txt", "r") as fh:
# fh.readlines() returns a list of all lines in the file as a string
# They all end with a newline so rstrip removes the newline character
data = [line.rstrip() for line in fh.readlines()]
seed_num_List = [int(num) for num in numre.findall(data[0])]
seed_ranges = [(seed_num_List[i], seed_num_List[i + 1]) for i in range(0, len(seed_num_List), 2)]
for i in range(2, len(data)):
line = data[i]
# Ignore empty lines
if len(line) == 0:
continue
# Try to find numbers in the line
num_matches = [int(num) for num in numre.findall(line)]
# No number found => Section heading
if len(num_matches) == 0:
mapping_sections.append([])
continue
# Numbers found => Process a mapping line
mapping_sections[-1].append(tuple(num_matches))Editor is loading...
Leave a Comment