prettify and lint optimization
This commit is contained in:
@@ -1,20 +1,21 @@
|
||||
def parse_file(file_path):
|
||||
"""Parse the input file to extract instructions and the node map."""
|
||||
try:
|
||||
with open(file_path, 'r') as file:
|
||||
with open(file_path, "r") as file:
|
||||
lines = file.readlines()
|
||||
|
||||
instructions = lines[0].strip()
|
||||
node_map = {}
|
||||
for line in lines[2:]:
|
||||
node, neighbors = line.strip().split(' = ')
|
||||
node_map[node] = tuple(neighbors[1:-1].split(', '))
|
||||
node, neighbors = line.strip().split(" = ")
|
||||
node_map[node] = tuple(neighbors[1:-1].split(", "))
|
||||
|
||||
return instructions, node_map
|
||||
except Exception as e:
|
||||
print(f"Error parsing file {file_path}: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def find_repeating_unit(sequence):
|
||||
"""Find the repeating unit in a sequence."""
|
||||
for i in range(1, len(sequence) + 1):
|
||||
@@ -23,7 +24,8 @@ def find_repeating_unit(sequence):
|
||||
return unit
|
||||
return sequence
|
||||
|
||||
def navigate_network(instructions, node_map, start_node='AAA', end_node='ZZZ'):
|
||||
|
||||
def navigate_network(instructions, node_map, start_node="AAA", end_node="ZZZ"):
|
||||
"""Navigate the network based on the instructions and return the number of steps."""
|
||||
current_node = start_node
|
||||
steps = 0
|
||||
@@ -33,28 +35,34 @@ def navigate_network(instructions, node_map, start_node='AAA', end_node='ZZZ'):
|
||||
|
||||
while current_node != end_node:
|
||||
if (current_node, instruction_index) in visited:
|
||||
print(f"Loop detected at {current_node} with instruction index {instruction_index}")
|
||||
print(
|
||||
f"Loop detected at {current_node} with instruction index {instruction_index}"
|
||||
)
|
||||
return -1 # Indicates a loop without reaching the end node
|
||||
|
||||
visited.add((current_node, instruction_index))
|
||||
direction = instructions[instruction_index % len(instructions)]
|
||||
current_node = node_map[current_node][0 if direction == 'L' else 1]
|
||||
current_node = node_map[current_node][0 if direction == "L" else 1]
|
||||
instruction_index += 1
|
||||
steps += 1
|
||||
|
||||
return steps
|
||||
|
||||
|
||||
def run_test():
|
||||
"""Run the test with the provided file path."""
|
||||
try:
|
||||
expected_result = 6
|
||||
instructions, node_map = parse_file("../test.txt")
|
||||
result = navigate_network(instructions, node_map)
|
||||
assert result == expected_result, f"Test failed, expected {expected_result} but got {result}"
|
||||
assert (
|
||||
result == expected_result
|
||||
), f"Test failed, expected {expected_result} but got {result}"
|
||||
print(f"Test passed with {result} steps.")
|
||||
except AssertionError as error:
|
||||
print(error)
|
||||
|
||||
|
||||
def main():
|
||||
print("Start Tests")
|
||||
run_test()
|
||||
@@ -70,5 +78,6 @@ def main():
|
||||
except Exception as e:
|
||||
print(f"Error during main execution: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import sys
|
||||
from math import gcd
|
||||
|
||||
|
||||
def parse_file(file_path):
|
||||
print(f"Parsing file: {file_path}")
|
||||
with open(file_path, 'r') as file:
|
||||
with open(file_path, "r") as file:
|
||||
D = file.read().strip()
|
||||
steps, rule = D.split('\n\n')
|
||||
GO = {'L': {}, 'R': {}}
|
||||
for line in rule.split('\n'):
|
||||
st, lr = line.split('=')
|
||||
left, right = lr.split(',')
|
||||
GO['L'][st.strip()] = left.strip()[1:].strip()
|
||||
GO['R'][st.strip()] = right[:-1].strip()
|
||||
return [0 if char == 'L' else 1 for char in steps], GO
|
||||
steps, rule = D.split("\n\n")
|
||||
GO = {"L": {}, "R": {}}
|
||||
for line in rule.split("\n"):
|
||||
st, lr = line.split("=")
|
||||
left, right = lr.split(",")
|
||||
GO["L"][st.strip()] = left.strip()[1:].strip()
|
||||
GO["R"][st.strip()] = right[:-1].strip()
|
||||
return [0 if char == "L" else 1 for char in steps], GO
|
||||
|
||||
|
||||
def lcm(xs):
|
||||
ans = 1
|
||||
@@ -20,16 +21,17 @@ def lcm(xs):
|
||||
ans = (x * ans) // gcd(x, ans)
|
||||
return ans
|
||||
|
||||
|
||||
def navigate_network_simultaneously(steps, GO):
|
||||
print("Starting navigation of network.")
|
||||
POS = [s for s in GO['L'] if s.endswith('A')]
|
||||
POS = [s for s in GO["L"] if s.endswith("A")]
|
||||
T = {}
|
||||
t = 0
|
||||
while True:
|
||||
NP = []
|
||||
for i, p in enumerate(POS):
|
||||
p = GO['L' if steps[t % len(steps)] == 0 else 'R'][p]
|
||||
if p.endswith('Z'):
|
||||
p = GO["L" if steps[t % len(steps)] == 0 else "R"][p]
|
||||
if p.endswith("Z"):
|
||||
T[i] = t + 1
|
||||
if len(T) == len(POS):
|
||||
print(f"All paths reached 'Z' nodes at step {t + 1}.")
|
||||
@@ -40,19 +42,24 @@ def navigate_network_simultaneously(steps, GO):
|
||||
print(f"Step {t}: Current nodes - {POS}")
|
||||
assert False
|
||||
|
||||
|
||||
def run_test():
|
||||
print("Running test...")
|
||||
expected_result = 6
|
||||
steps, GO = parse_file("../test2.txt")
|
||||
result = navigate_network_simultaneously(steps, GO)
|
||||
assert result == expected_result, f"Test failed, expected {expected_result} but got {result}"
|
||||
assert (
|
||||
result == expected_result
|
||||
), f"Test failed, expected {expected_result} but got {result}"
|
||||
print(f"Test passed with {result} steps.")
|
||||
|
||||
|
||||
def main():
|
||||
run_test()
|
||||
steps, GO = parse_file("../input.txt")
|
||||
result = navigate_network_simultaneously(steps, GO)
|
||||
print(f"All paths reached 'Z' nodes simultaneously in {result} steps.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user