Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions puzzles/solutions/2023/d01/p1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import re
import sys


def calculate_calibration_values_sum(input_text: str) -> int:
calibration_values_sum = 0
for line in input_text.splitlines():
numbers = re.findall(r"\d", line)
calibration_value = int(numbers[0]) * 10 + int(numbers[-1])
calibration_values_sum += calibration_value
return calibration_values_sum


def get_answer(input_text: str) -> int:
"""Return the calibrations values sum."""
return calculate_calibration_values_sum(input_text)


if __name__ == "__main__":
try:
print(get_answer(sys.argv[1]))
except IndexError:
pass # Don't crash if no input was passed through command line arguments.
37 changes: 37 additions & 0 deletions puzzles/solutions/2023/d01/p2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import sys

import p1


DIGITS_NAMES_TO_NUMBERS = dict(
zip(
("one", "two", "three", "four", "five", "six", "seven", "eight", "nine"),
(map(str, range(1, 10))),
)
)


def _convert_digits_names_to_numbers(input_text: str) -> str:
new_text = ""
for line in input_text.splitlines():
new_line = line[0]
for i in range(1, len(line)):
new_line += line[i]
for digit_name in DIGITS_NAMES_TO_NUMBERS:
if line.endswith(digit_name, 0, i + 1):
new_line += DIGITS_NAMES_TO_NUMBERS[digit_name]
new_text += new_line + "\n"
return new_text


def get_answer(input_text: str):
"""Return the calibrations values sum where digits names are replaced with numbers."""
input_text = _convert_digits_names_to_numbers(input_text)
return p1.calculate_calibration_values_sum(input_text)


if __name__ == "__main__":
try:
print(get_answer(sys.argv[1]))
except IndexError:
pass # Don't crash if no input was passed through command line arguments.