prettify and lint optimization

This commit is contained in:
2023-12-10 17:24:14 +01:00
parent 274c69d0c4
commit 4cd62ef794
32 changed files with 599 additions and 262 deletions

View File

@@ -14,7 +14,7 @@ def extract_calibration_value(line):
if char.isdigit():
first_digit = char
break
# Find the last digit in the line
for char in reversed(line):
if char.isdigit():
@@ -27,6 +27,7 @@ def extract_calibration_value(line):
else:
return 0
def sum_calibration_values(filename):
"""
Calculate the sum of all calibration values in the document.
@@ -37,12 +38,13 @@ def sum_calibration_values(filename):
total = 0
# Open the file and process each line
with open(filename, 'r') as file:
with open(filename, "r") as file:
for line in file:
total += extract_calibration_value(line)
return total
# Main execution
if __name__ == "__main__":
filename = "../input.txt"

View File

@@ -1,8 +1,16 @@
def extract_digits(line):
"""Extracts all digits (as numbers) from the line in the order they appear."""
digit_map = {
"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4",
"five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}
# Add single digit mappings
@@ -11,17 +19,15 @@ def extract_digits(line):
digits_found = []
i = 0
while i < len(line):
matched = False
for word, digit in digit_map.items():
if line.startswith(word, i):
digits_found.append(int(digit))
i += len(word) - 1 # Advance the index
matched = True
break
i += 1 # Move to the next character if no match
return digits_found
def extract_calibration_value(line):
"""Extracts the calibration value from a line."""
digits = extract_digits(line)
@@ -29,10 +35,11 @@ def extract_calibration_value(line):
return int(str(digits[0]) + str(digits[-1]))
return 0
def sum_calibration_values(file_path):
"""Extracts calibration values from each line and sums them up."""
total_sum = 0
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
for line in file:
calibration_value = extract_calibration_value(line.strip())
if calibration_value:
@@ -44,9 +51,11 @@ def sum_calibration_values(file_path):
return total_sum
# Main execution
if __name__ == "__main__":
import sys
filename = sys.argv[1] if len(sys.argv) > 1 else "../input.txt"
total_calibration_value = sum_calibration_values(filename)
print(f"Total Sum of Calibration Values: {total_calibration_value}")