From 09d24e0c2f22ad67ed45395b56e0d49f1a1d047c Mon Sep 17 00:00:00 2001 From: kwout Date: Fri, 1 Dec 2023 12:27:20 -0500 Subject: [PATCH] solved 2023 day 1b and made 1a better --- 2023/day1/1a.py | 17 ++++++++++++++--- 2023/day1/1b.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 2023/day1/1b.py diff --git a/2023/day1/1a.py b/2023/day1/1a.py index 054de9d..b3bfdb1 100644 --- a/2023/day1/1a.py +++ b/2023/day1/1a.py @@ -3,7 +3,18 @@ lines = [i for i in open("input.txt", 'r').read().splitlines()] sum = 0 for l in lines: - n = "".join(c for c in l if not c.isalpha()) - sum += int(n[0] + n[-1]) - + first = "" + firstFound = False + last = "" + lastFound = False + for i in range(len(l)): + if not firstFound and l[i].isnumeric(): + first = l[i] + firstFound = True + if not lastFound and l[-i-1].isnumeric(): + last = l[-i-1] + lastFound = True + if firstFound and lastFound: + continue + sum += int(first + last) print(sum) \ No newline at end of file diff --git a/2023/day1/1b.py b/2023/day1/1b.py new file mode 100644 index 0000000..f844fd1 --- /dev/null +++ b/2023/day1/1b.py @@ -0,0 +1,32 @@ +lines = [i for i in open("input.txt", 'r').read().splitlines()] + +sum = 0 +words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] + +for l in lines: + first = "" + firstFound = False + last = "" + lastFound = False + n = len(l) + for i in range(n): + if not firstFound and l[i].isnumeric(): + first = l[i] + firstFound = True + if not lastFound and l[-i-1].isnumeric(): + last = l[-i-1] + lastFound = True + for j in range(len(words)): + m = len(words[j]) + if not firstFound and l[i:i+m] == words[j]: + first = str(j) + firstFound = True + if not lastFound and l[-(i+m):n-i] == words[j]: + last = str(j) + lastFound = True + if firstFound and lastFound: + break + s = first + last + sum += int(s) + +print(sum) \ No newline at end of file