advent-of-code/2023/python/day01.py
2023-12-01 10:31:20 -05:00

67 lines
1.3 KiB
Python

import matrix
import shared
import itertools
import functools
NUMS = {
"one": 1,
"two": 2,
"six": 6,
"four": 4,
"five": 5,
"nine": 9,
"seven": 7,
"eight": 8,
"three": 3,
}
# @shared.profile
def part1(rows):
total = 0
for row in rows:
numbers = ''.join(filter(str.isdigit, row))
total += get_total(numbers)
print(total)
def get_total(numbers):
tens, ones= int(numbers[0]),int(numbers[-1])
return (tens * 10) + ones
def loop_row(row):
digits = []
for idx, _ in enumerate(row):
if str.isdigit(row[idx]):
digits.append(row[idx])
continue
for x in [3,4,5]:
next = row[idx:idx+x]
if next in NUMS.keys():
digits.append(str(NUMS[next]))
break
return "".join(digits)
# @shared.profile
def part2(rows):
total = 0
for row in rows:
nums = loop_row(row)
total += get_total(nums)
print(total)
def main():
rows = [row for row in shared.load_rows(1)]
with shared.elapsed_timer() as elapsed:
#part1(rows)
print("🕒", elapsed())
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()