Star 1
We are tasked with finding a two-digit number hidden in each line of text.
The number is found by combining the first digit and the last digit.
Ex. 12 in 1abc2
My solution parses through each line, once from the front and once from the back.
This finds the first and last character that isNumeric() and then adds it to the total.
contents = open("day1.txt").read().splitlines()
total = 0
string = ''
for line in contents:
for val in line:
if val.isnumeric():
string += val
break
line = line[::-1]
for val in line:
if val.isnumeric():
string += val
break
total += int(string)
string = ''
print(total)
Star 2
For Star 2, the big difference is that written digits (one, two, three, etc) also count as valid "digits".
Ex. 7pqrstsixteen = 76
My solution uses a different approach than Star 1. I first convert the string into its collection of digits:
4nineeightseven2 = "49872" and I then take the first and last value in the string.
contents = open("day1.txt").read().splitlines()
total = 0
list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
for line in contents:
string = ''
for i, val in enumerate(line):
if val.isnumeric():
string += val
for val in list:
if line[i:].startswith(val):
string += str(list.index(val) + 1)
total += int(string[0] + string[-1])
print(total)