Untitled
unknown
python
3 years ago
1.3 kB
8
Indexable
import re
with open('crates.txt', 'r') as fd:
stack_string = ''
instructions = []
for line in fd.readlines():
if not line.startswith('move'):
stack_string += line
else:
instructions.append(line.strip())
def rearrange_stack(stack):
number_of_stacks = int(max(re.findall(r'\d+', stack)))
stacks = [[] for i in range(number_of_stacks)]
for line in stack.split('\n'):
for idx, char in enumerate(line):
if char.isalpha():
stacks[idx // 4].insert(0, char)
return stacks
stacks = rearrange_stack(stack_string)
for instruction in instructions:
_, amount, _, src, _, dst = instruction.split(' ')
amount, src, dst = int(amount), int(src) - 1, int(dst) - 1
for idx in range(amount):
stacks[dst].append(stacks[src].pop())
top_crates = ''
for stack in stacks:
top_crates += stack[-1]
print(stacks)
print(top_crates)
stacks = rearrange_stack(stack_string)
for instruction in instructions:
_, amount, _, src, _, dst = instruction.split(' ')
amount, src, dst = int(amount), int(src) - 1, int(dst) - 1
moving_crates = stacks[src][-amount:]
stacks[src][-amount:] = []
stacks[dst].extend(moving_crates)
top_crates = ''
for stack in stacks:
top_crates += stack[-1]
print(stacks)
print(top_crates)
Editor is loading...