-
Notifications
You must be signed in to change notification settings - Fork 0
/
06.py
executable file
·50 lines (37 loc) · 1.09 KB
/
06.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
#!/usr/bin/env python3
import sys
def parse_input(filename):
lines = open(filename).read().splitlines()
return {y: x for x, y in map(lambda x: x.split(")"), lines)}
def depth(orbits, obj):
count = 0
parent = obj
while parent != "COM":
parent = orbits[parent]
count += 1
return count
def part1(orbits):
return sum(map(lambda x: depth(orbits, x), orbits.keys()))
def part2(orbits):
# Assume that the graph is acyclic and therefore we only need to
# calculate the distance until YOU and SAN intersect. Otherwise, we
# would have to use a shortest path algorithm such as the Dijkstra's
# algorithm.
obj = orbits["YOU"]
count = 0
distances = {}
while obj != "COM":
distances[obj] = count
obj = orbits[obj]
count += 1
obj = orbits["SAN"]
count = 0
while obj != "COM":
if obj in distances:
return distances[obj] + count
obj = orbits[obj]
count += 1
return None
orbits = parse_input(sys.argv[1])
print("Part 1:", part1(orbits))
print("Part 1:", part2(orbits))