refactor to remove re

This commit is contained in:
Dmitry Fedotov
2023-12-09 14:35:12 +03:00
parent 7fcf650d6e
commit 3335c493cb

View File

@@ -28,7 +28,7 @@ def solve1(lines) -> int:
def solve2(lines) -> int: def solve2(lines) -> int:
total = 0 total = 0
for l in lines: for l in lines:
l = to_digits(l) l = replace_word_with_digit(l)
total += findsum(l) total += findsum(l)
return total return total
@@ -41,7 +41,6 @@ def findsum(line):
def find_digit(line, reverse=False): def find_digit(line, reverse=False):
val = '' val = ''
idx = None
start, end, step = 0, len(line), 1 start, end, step = 0, len(line), 1
if reverse: if reverse:
start, end, step = len(line)-1, -1, -1 start, end, step = len(line)-1, -1, -1
@@ -51,16 +50,31 @@ def find_digit(line, reverse=False):
break break
return val return val
def to_digits(line): def replace_word_with_digit(line):
m = re_digit.findall(line) start, end, step = 0, len(line), 1
if not m: found = False
return line for i in range(start, end, step):
# since words may overlap (e.g. in 'oneight' or 'twone'), we'll for word in digits_dict.keys():
# replace the ocurrence of first and last (possibly overlapping) matches if line[i:].startswith(word):
# and return combined string. # just inserting the digit so that our
l1 = re.sub(m[0], digits_dict[m[0]], line, count=1) # find_digit func can help with the rest
l2 = re.sub(m[-1], digits_dict[m[-1]], line) line = line[:i] + digits_dict[word] + line[i:]
return l1+l2 found = True
break
if found:
break
start, end, step = len(line), -1, -1
found = False
for i in range(start, end, step):
for word in digits_dict.keys():
if line[:i].endswith(word):
line = line[:i] + digits_dict[word]+line[i:]
found = True
break
if found:
break
return line
if __name__ == '__main__': if __name__ == '__main__':
@@ -77,3 +91,4 @@ if __name__ == '__main__':
print(y) print(y)