-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01p2.py
46 lines (36 loc) · 1.06 KB
/
01p2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
input = open("01-input.txt", "r")
calibrationValues = []
textDigits = {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine"
}
for line in input:
lineValue = line.strip()
# replace all numeric values by textual representation
for number, textNumber in textDigits.items():
lineValue = lineValue.replace(number, textNumber)
lowestFirstIndex = 1000
lowestFirstIndexKey = ""
lowestLastIndex = -1
lowestLastIndexKey = ""
# search from the begining
for number, textNumber in textDigits.items():
found = lineValue.find(textNumber)
if (found >= 0 and found < lowestFirstIndex):
lowestFirstIndex = found
lowestFirstIndexKey = number
# search from the end
for number, textNumber in textDigits.items():
found = lineValue.rfind(textNumber)
if (found >= 0 and found > lowestLastIndex):
lowestLastIndex = found
lowestLastIndexKey = number
calibrationValues.append(int(lowestFirstIndexKey + lowestLastIndexKey))
print(sum(calibrationValues))