Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 5, 2022 18:09
Embed
What would you like to do?
# Read the input from the file and parse it
with open("input.txt") as f:
lines = f.readlines()
# Create the initial stacks of crates by splitting the first three lines of the input
stack1 = list(lines[0].strip())
stack2 = list(lines[1].strip())
stack3 = list(lines[2].strip())
# Define the movement steps as a list of tuples, where each tuple
# contains the source stack, the destination stack, and the number of crates to move
steps = []
for line in lines[4:]:
# Skip empty lines
if not line.strip():
continue
# Strip leading and trailing whitespace from the line, then split it into individual words
# and convert the source and destination stacks to integers
words = line.strip().split()
source = int(words[1])
dest = int(words[3])
# Convert the number of crates to move to an integer and append it to the tuple
print(words)
num_crates = int(words[4])
step = (source, dest, num_crates)
steps.append(step)
# Loop through the steps and simulate the movement of the crates
for step in steps:
# Unpack the source stack, destination stack, and number of crates from the tuple
source, dest, num_crates = step
# Move the crates from the source stack to the destination stack
for i in range(num_crates):
if source == 1:
# Move a crate from stack1 to the destination stack
crate = stack1.pop()
if dest == 2:
stack2.append(crate)
elif dest == 3:
stack3.append(crate)
elif source == 2:
# Move a crate from stack2 to the destination stack
crate = stack2.pop()
if dest == 1:
stack1.append(crate)
elif dest == 3:
stack3.append(crate)
elif source == 3:
# Move a crate from stack3 to the destination stack
crate = stack3.pop()
if dest == 1:
stack1.append(crate)
elif dest == 2:
stack2.append(crate)
# Determine the top crate on each stack
top1 = stack1[-1]
top2 = stack2[-1]
top3 = stack3[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment