-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
66 lines (52 loc) · 1.82 KB
/
solution.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from pathlib import Path
from functools import cmp_to_key
def getInput(path: str) -> list[str]:
input = Path(path).read_text().replace("\n\n", "\n").splitlines()
return input
def compare(left, right) -> int:
result = 0
# Turn items into lists if they aren't already
if not isinstance(left, list):
left = [left]
if not isinstance(right, list):
right = [right]
# Iterate through items, recursively calling compare if an item is a list
for i in range(min(len(left), len(right))):
# Check if either item is a list
if isinstance(left[i], list) or isinstance(right[i], list):
result = compare(left[i], right[i])
if result != 0:
return result
# current items are not lists, compare them
elif left[i] < right[i]:
return -1
elif left[i] > right[i]:
return 1
# Iterated through all items in one or both lists. Compare lengths
if len(left) < len(right):
return -1
if len(left) > len(right):
return 1
return 0 # Lists are identical
def part1(input: list[str]) -> str:
input = list(map(eval, input))
pairs = [input[i : i + 2] for i in range(0, len(input), 2)]
total = 0
for idx, pair in enumerate(pairs, 1):
result = compare(pair[0], pair[1])
if result <= 0:
total += idx
return str(total)
def part2(input: list[str]) -> str:
input = list(map(eval, input))
input.extend([[[2]], [[6]]])
input = sorted(input, key=cmp_to_key(compare))
idx1, idx2 = input.index([[2]]) + 1, input.index([[6]]) + 1
return str(idx1 * idx2)
def main():
input = getInput("input.txt")
print(f"Answer to part 1: {part1(input)}")
print(f"Answer to part 2: {part2(input)}")
return
if __name__ == "__main__":
main()