This repository has been archived on 2024-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
aoc2023/lib.py
felixm 9485fbae1d Solve day 9 and fix horrible bug in lib.
My integer parser did not consider negative values. I have fixed that
in the 2022 repository, but not here. That's pretty annoying.
2023-12-09 11:48:39 -05:00

51 lines
1.2 KiB
Python

import re
def prime_factors(n):
"""
Returns a list of prime factors for n.
:param n: number for which prime factors should be returned
"""
factors = []
rest = n
divisor = 2
while rest % divisor == 0:
factors.append(divisor)
rest //= divisor
divisor = 3
while divisor * divisor <= rest:
while rest % divisor == 0:
factors.append(divisor)
rest //= divisor
divisor += 2
if rest != 1:
factors.append(rest)
return factors
def lcm(numbers: list[int]) -> int:
fs = []
for n in numbers:
fs += prime_factors(n)
s = 1
fs = list(set(fs))
for f in fs:
s *= f
return s
def str_to_single_int(line: str) -> int:
line = line.replace(" ", "")
r = re.compile(r"-?\d+")
for m in r.findall(line):
return int(m)
raise Exception("No single digit sequence in '{line}'")
def str_to_int_list(line: str) -> list[int]:
r = re.compile(r"-?\d+")
return list(map(int, r.findall(line)))
def str_to_lines_no_empty(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def str_to_lines(text: str) -> list[str]:
return list(text.splitlines())