1
+ from collections import defaultdict
2
+
3
+ # read input
4
+ input = open ('input.txt' , 'r' )
5
+ lines = input .readlines ()
6
+
7
+ # variables
8
+ stacksOfCrates = []
9
+ procedures = False
10
+ stackColumns = defaultdict (list )
11
+ topCrates = ''
12
+
13
+ # get indices of crates
14
+ def getCrateIndex (columnIndex ):
15
+ return columnIndex * 4 - 3
16
+
17
+ # construct list of stacks of marked crates
18
+ for index , line in enumerate (lines ):
19
+ line = line .split ('\n ' )[0 ]
20
+ if (line == '' ):
21
+ break
22
+ else :
23
+ stacksOfCrates .append (line )
24
+
25
+ totalColumns = int (stacksOfCrates [- 1 ].split ()[- 1 ])
26
+ stacksOfCrates = stacksOfCrates [:- 1 ]
27
+
28
+ # construct dictionary of stacks of marked crates
29
+ for stackRow in stacksOfCrates :
30
+ for columnIndex in range (1 , totalColumns + 1 ):
31
+ crateIndex = getCrateIndex (columnIndex )
32
+ if (stackRow [crateIndex ] != ' ' ):
33
+ stackColumns [columnIndex ].append (stackRow [crateIndex ])
34
+
35
+ # print(stackColumns)
36
+
37
+ # rearrange crates in stacks of marked crates
38
+ def rearrangeCrates (cratesQuantity , fromStack , toStack ):
39
+ cratesMoved = stackColumns [fromStack ][0 :cratesQuantity ]
40
+ del stackColumns [fromStack ][0 :cratesQuantity ]
41
+ for crates in cratesMoved :
42
+ stackColumns [toStack ].insert (0 , crates )
43
+
44
+ # apply set of procedures
45
+ for line in lines :
46
+ line = line .split ('\n ' )[0 ]
47
+ if (procedures ):
48
+ procedureList = line .split ()
49
+ cratesQuantity = int (procedureList [1 ])
50
+ fromStack = int (procedureList [3 ])
51
+ toStack = int (procedureList [5 ])
52
+ rearrangeCrates (cratesQuantity , fromStack , toStack )
53
+ if (line == '' ):
54
+ procedures = True
55
+
56
+ # print(stackColumns)
57
+
58
+ for key in range (1 , len (stackColumns ) + 1 ):
59
+ topCrates += stackColumns [key ][0 ]
60
+
61
+ # part one
62
+ print ('Top crates: ' , topCrates )
63
+
64
+ # part two
0 commit comments