51 lines
1.3 KiB
Python
Executable File
51 lines
1.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
from functools import reduce
|
|
import re, sys
|
|
import sys
|
|
|
|
def single(b):
|
|
return ' '.join(b.split()[1:3])
|
|
|
|
def multiple(b):
|
|
name = ' '.join(b.split()[1:3])
|
|
num = b.split()[0]
|
|
if num == 'no':
|
|
return 'empty', 0
|
|
return name, int(num)
|
|
|
|
def tpl(l): # get nice tuple from line
|
|
me, rest = l[:-1].split(' bags contain ') # space separated fields
|
|
return me, [single(r) for r in rest.split(', ')]
|
|
|
|
def dic(l): # get nice dict from line
|
|
me, rest = l[:-1].split(' bags contain ') # space separated fields
|
|
return me, {k: v for k, v in (multiple(r) for r in rest.split(', '))}
|
|
|
|
gold = 'shiny gold'
|
|
|
|
def has_gold(dic, b):
|
|
acc = []
|
|
for k in dic:
|
|
if b in dic[k]:
|
|
acc += [k,] + has_gold(dic, k)
|
|
return acc
|
|
|
|
def gold_has(dic, b, lvl=0):
|
|
if(b == 'empty'):
|
|
return 0
|
|
acc = 1
|
|
for k in dic[b]:
|
|
acc += dic[b][k] * gold_has(dic, k, lvl=lvl+1)
|
|
print(' '*lvl + '%s * %s...' % (dic[b][k], k), acc)
|
|
return acc
|
|
|
|
fn = sys.argv[1] if len(sys.argv) > 1 else 'input7'
|
|
with open(fn) as f:
|
|
|
|
lines = [l.strip() for l in f.readlines()]
|
|
pic = {a: b for a, b in (tpl(l) for l in lines)}
|
|
print(len(set(has_gold(pic, gold))))
|
|
duc = {a: b for a, b in (dic(l) for l in lines)}
|
|
print(duc)
|
|
print(gold_has(duc, gold) - 1)
|