59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
import os
|
|
import re
|
|
|
|
cwd = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
# file_name = 'advent2023_p1.txt'
|
|
file_name = 'test.txt'
|
|
advent = os.path.join(cwd, file_name)
|
|
|
|
nums = []
|
|
values = []
|
|
|
|
# test = "eighthree"
|
|
|
|
# numbers = {
|
|
# 'one': 1, 'two': 2, 'three': 3, 'four': 4,
|
|
# 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9
|
|
# }
|
|
numbers_to_string = {
|
|
'one': '1', 'two': '2', 'three': '3', 'four': '4',
|
|
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'
|
|
}
|
|
|
|
|
|
|
|
with open(advent, 'r') as file:
|
|
for line in file: # Read lines
|
|
# Split the line when a digit has been found
|
|
digit_index = re.findall(r'(?:(one|two|three|four|five|six|seven|eight|nine)|(\d))', line)
|
|
# print(digit_index)
|
|
if digit_index:
|
|
# Use the tuple method to find if the value is present
|
|
for num,num2 in digit_index:
|
|
# Always the spelled out number, convert to string digit
|
|
if num:
|
|
# if num in numbers:
|
|
# nums.append()
|
|
nums.append(numbers_to_string[num])
|
|
# Pass the string digit
|
|
if num2:
|
|
nums.append(num2)
|
|
print(nums)
|
|
# values.append()
|
|
if len(nums) < 2:
|
|
num_one = nums[0]
|
|
num_two = num_one
|
|
num_join = num_one + num_two
|
|
values.append(int(num_join))
|
|
else:
|
|
num_one = nums[0]
|
|
num_two = nums[-1]
|
|
num_join = num_one + num_two
|
|
values.append(int(num_join))
|
|
nums.clear()
|
|
# print(values)
|
|
# print(sum(values))
|
|
# print(numbers_as_integers)
|
|
|
|
file.close() |