advent-of-code/2023/python/day01.py

69 lines
1.3 KiB
Python
Raw Normal View History

2023-12-01 15:31:20 +00:00
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,
}
2023-12-08 18:42:42 +00:00
2023-12-01 15:31:20 +00:00
# @shared.profile
def part1(rows):
total = 0
for row in rows:
2023-12-08 18:42:42 +00:00
numbers = "".join(filter(str.isdigit, row))
2023-12-01 15:31:20 +00:00
total += get_total(numbers)
print(total)
2023-12-08 18:42:42 +00:00
2023-12-01 15:31:20 +00:00
def get_total(numbers):
2023-12-08 18:42:42 +00:00
tens, ones = int(numbers[0]), int(numbers[-1])
2023-12-01 15:31:20 +00:00
return (tens * 10) + ones
2023-12-08 18:42:42 +00:00
2023-12-01 15:31:20 +00:00
def loop_row(row):
digits = []
for idx, _ in enumerate(row):
if str.isdigit(row[idx]):
digits.append(row[idx])
continue
2023-12-08 18:42:42 +00:00
for x in [3, 4, 5]:
next = row[idx : idx + x]
2023-12-01 15:31:20 +00:00
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)
2023-12-08 18:42:42 +00:00
2023-12-01 15:31:20 +00:00
def main():
rows = [row for row in shared.load_rows(1)]
with shared.elapsed_timer() as elapsed:
2023-12-03 04:12:04 +00:00
part1(rows)
2023-12-01 15:31:20 +00:00
print("🕒", elapsed())
2023-12-03 04:12:04 +00:00
rows = [row for row in shared.load_rows(1, True)]
2023-12-01 15:31:20 +00:00
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()