-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_08.py
More file actions
73 lines (47 loc) · 1.62 KB
/
Day_08.py
File metadata and controls
73 lines (47 loc) · 1.62 KB
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
67
68
69
70
71
72
73
from time import perf_counter
start_time = perf_counter()
def open_file(file_name: str = "Day_08.txt") -> str:
with open(file_name) as f:
return f.read()
def populate_graph(lines: list[str]) -> dict[str, dict[str, str]]:
graph = {}
for line in lines:
graph[line[0:3]] = {"L": line[7:10], "R": line[12:15]}
return graph
def part_one(graph, order) -> int:
current_node = "AAA"
result = 0
while current_node != "ZZZ":
step = result % len(order)
current_node = graph[current_node][order[step]]
result += 1
return result
def greatest_common_divisor(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def least_common_multiple(numbers_list: list[int]) -> int:
result = numbers_list[0]
for i in numbers_list[1:]:
result = result * i // greatest_common_divisor(result, i)
return result
def part_two(starting_nodes, graph, order) -> int:
results = []
for current_node in starting_nodes:
result = 0
while current_node[2] != "Z":
step = result % len(order)
current_node = graph[current_node][order[step]]
result += 1
results.append(result)
return least_common_multiple(results)
def main():
lines = open_file().splitlines()
graph = populate_graph(lines[2:])
order = lines[0]
print("Part 1: ", part_one(graph, order))
starting_nodes = (key for key in graph.keys() if key[2] == "A")
print("Part 2: ", part_two(starting_nodes, graph, order))
if __name__ == "__main__":
main()
print("Time elapsed: ", perf_counter() - start_time)