Facebook
From Bistre Curlew, 2 Years ago, written in Python.
Embed
Download Paste or View Raw
Hits: 144
  1. import re
  2.  
  3. # Fetch input data
  4. with open('input.txt') as input_data:
  5.     input_data = input_data.readlines()
  6.     stacks = [stack.strip('\n') for stack in input_data[:8]]
  7.     instructions = [line.strip() for line in input_data[10:]]
  8.  
  9.     # Create starting stacks as lists/saving lists to dict
  10.     one = []
  11.     two = []
  12.     three = []
  13.     four = []
  14.     five = []
  15.     six = []
  16.     seven = []
  17.     eight = []
  18.     nine = []
  19.  
  20.     stacks_dict = {
  21.         '1':one,
  22.         '2':two,
  23.         '3':three,
  24.         '4':four,
  25.         '5':five,
  26.         '6':six,
  27.         '7':seven,
  28.         '8': eight,
  29.         '9': nine,
  30.         }
  31.  
  32.     for crate in stacks:
  33.         if crate[:4] != '    ':
  34.             one.append(crate[1])
  35.         if crate[4:8] != '    ':
  36.             two.append(crate[5])
  37.         if crate[8:12] != '    ':
  38.             three.append(crate[9])
  39.         if crate[12:16] != '   ':
  40.             four.append(crate[13])
  41.         if crate[16:20] != '   ':
  42.             five.append(crate[17])  
  43.         if crate[12:16] != '   ':
  44.             six.append(crate[21])  
  45.         if crate[16:20] != '   ':
  46.             seven.append(crate[25])
  47.         if crate[20:24] != '   ':
  48.             eight.append(crate[29])
  49.         if crate[24:27] != '  ':
  50.             nine.append(crate[33])    
  51.        
  52.     # Tidy up empty list elements
  53.     for stack in stacks_dict.keys():
  54.         stacks_dict[stack] = [crate for crate in stacks_dict[stack] if crate != ' ']
  55.    
  56.  
  57.     # Follow instrcution to move crates across stacks
  58.     for instruction in instructions:
  59.         quanity, source, dest = re.findall(r'[0-9][0-9]*', instruction)
  60.         move = stacks_dict[source][:int(quanity)]
  61.         for x in move:
  62.             stacks_dict[source].remove(x)
  63.         stacks_dict[dest] = move + stacks_dict[dest]
  64.          
  65. # Concatente first element of list to find answer
  66. answer = ''
  67. for stack in stacks_dict.values():
  68.     answer += stack[0]
  69.  
  70. print(answer)