+/AoC
advent of code
git clone https://git.julia.blue/+/AoC
38c0746
master
1from itertools import product 2 3 4class Program (): 5 6def __init__ (self ,n ,w ,c = []): 7self .name = n 8self .weight = w 9self .children = c 10 11def updateChildren (self ,proglist ): 12self .children = [i [1 ]for i in product (self .children ,proglist )if i [0 ]== i [1 ].name ] 13 14def getTotalChildren (self ): 15return len (self .children )+ sum (i .getTotalChildren ()for i in self .children ) 16 17def updateTotalWeight (self ): 18self .totalWeight = self .weight + sum (i .updateTotalWeight ()for i in self .children ) 19return self .totalWeight 20 21raw = map (lambda x :x .strip (),open ("input.txt" )) 22 23programs = [] 24for line in raw : 25line = line .replace (',' ,' ' ).split () 26programs .append (Program (line [0 ],int (line [1 ][1 :- 1 ]),line [3 :])) 27 28for p in programs : 29p .updateChildren (programs ) 30 31programs .sort (key = lambda p :p .getTotalChildren ()) 32 33"Part 1:" ,programs [- 1 ].name 34 35programs [- 1 ].updateTotalWeight () 36 37 38def balance (p ,needs = 0 ): 39if not p .children : 40return 41if len (set ([i .totalWeight for i in p .children ]))== 1 : 42return 43 44p .children .sort (key = lambda i :i .totalWeight ) 45if not needs : 46needs = p .children [- 1 ].totalWeight - p .children [0 ].totalWeight 47if p .children [0 ].totalWeight == p .children [1 ].totalWeight : 48needs = - needs 49 50kidsresults = [balance (i ,needs )for i in p .children ] 51if any (kidsresults ): 52return [i for i in kidsresults if i ][0 ] 53 54if needs > 0 : 55return p .children [0 ].weight + needs 56return p .children [- 1 ].weight + needs 57 58"Part 2:" ,balance (programs [- 1 ])