Solution to problem 6 part 1 in Python

This commit is contained in:
David Doblas Jiménez 2022-03-08 21:14:40 +01:00
parent d6fc9d7e55
commit 088cf71aa2

View File

@ -68,24 +68,30 @@
# What is the total number of direct and indirect orbits in your map data?
with open("files/test") as f:
with open("files/P6.txt") as f:
orbits = [line for line in f.read().strip().split()]
# print(orbits)
from collections import defaultdict
planets = defaultdict(list)
for orbit in orbits:
planet, satellite = orbit.split(")")
planets[planet].append(satellite)
def count_orbits(node, counter, total_sum):
def count_orbits(universe, node, counter, total_sum):
total_sum += counter
for satellite in planets[node]:
total_sum = count_orbits(satellite, counter + 1, total_sum)
for satellite in universe[node]:
total_sum = count_orbits(universe, satellite, counter + 1, total_sum)
return total_sum
print(count_orbits("COM", 0, 0))
def part_1():
universe = defaultdict(list)
for orbit in orbits:
planet, satellite = orbit.split(")")
universe[planet].append(satellite)
total_orbits = count_orbits(universe, "COM", 0, 0)
print(f"There are {total_orbits} in our universe")
if __name__ == "__main__":
part_1()