advent-of-code/2022/python/shared.py

103 lines
2.1 KiB
Python
Raw Normal View History

2022-12-11 05:44:32 +00:00
from contextlib import contextmanager
from timeit import default_timer
2022-12-09 16:43:00 +00:00
from pathlib import Path
2022-12-14 19:00:11 +00:00
import cProfile
import functools
import pstats
def profile(func):
@functools.wraps(func)
def inner(*args, **kwargs):
profiler = cProfile.Profile()
profiler.enable()
try:
retval = func(*args, **kwargs)
finally:
profiler.disable()
with open('profile.out', 'w') as profile_file:
stats = pstats.Stats(profiler, stream=profile_file)
stats.print_stats()
return retval
return inner
2022-12-09 16:43:00 +00:00
spl = lambda y: [int(w) for w in y]
2022-12-12 07:41:14 +00:00
2022-12-14 07:38:19 +00:00
def minmax(l):
return min(l),max(l)
2022-12-09 16:43:00 +00:00
def load_rows(day):
return [row for row in load(day)]
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def load(day):
path = Path(get_fname(day))
return path.read_text().rstrip().split("\n")
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def get_fname(day: int) -> str:
import sys
if sys.argv[-1] == "--sample":
return f"../samples/day{day:02}.txt"
else:
return f"../full/day{day:02}.txt"
#############
def load_char_matrix(f):
my_file = []
for line in f:
my_file.append(line.rstrip())
return [list(x) for x in my_file]
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def load_file_char_matrix(name):
with open(name, "r") as f:
return load_char_matrix(f)
def load_int_matrix(f):
my_file = []
for line in f:
my_file.append(line.rstrip())
return [list(map(int, x)) for x in my_file]
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def load_file_int_matrix(name):
with open(name, "r") as f:
return load_int_matrix(f)
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def load_word_matrix(f):
my_file = []
for line in f:
my_file.append(line.rstrip())
return [x.split(" ") for x in my_file]
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def load_file_word_matrix(name):
with open(name, "r") as f:
return load_word_matrix(f)
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
#############
2022-12-12 07:41:14 +00:00
2022-12-09 16:43:00 +00:00
def rotate(WHAT, times=1):
what = WHAT
for x in range(times):
what = list(zip(*what[::-1]))
return what
2022-12-11 05:44:32 +00:00
@contextmanager
def elapsed_timer():
start = default_timer()
elapser = lambda: default_timer() - start
yield lambda: elapser()
end = default_timer()
2022-12-12 07:41:14 +00:00
elapser = lambda: end - start