prettify and lint optimization

This commit is contained in:
2023-12-10 17:24:14 +01:00
parent 274c69d0c4
commit 4cd62ef794
32 changed files with 599 additions and 262 deletions

View File

@@ -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()