48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
|
from lib import get_data
|
||
|
|
||
|
|
||
|
def part_1(data):
|
||
|
bags = {}
|
||
|
for line in data.splitlines():
|
||
|
left, right = line.split(" contain ")
|
||
|
lb = " ".join(left.split()[:2])
|
||
|
rbs = right.replace(" bag", "").replace(" bags", "").replace(".", "").split(",")
|
||
|
if "no others" in rbs:
|
||
|
rbs = []
|
||
|
else:
|
||
|
rbs = [[int(v.split()[0]), " ".join(v.split()[1:])] for v in rbs]
|
||
|
assert lb not in bags
|
||
|
bags[lb] = rbs
|
||
|
|
||
|
for lb, rbs in bags.items():
|
||
|
for t in rbs:
|
||
|
if t[0] > 1:
|
||
|
t[1] = t[1][:-1]
|
||
|
|
||
|
can_hold = set(["shiny gold"])
|
||
|
can_hold_count = -1
|
||
|
while can_hold_count != len(can_hold):
|
||
|
can_hold_count = len(can_hold)
|
||
|
for lb, rbs in bags.items():
|
||
|
for _, bag_color in rbs:
|
||
|
if bag_color in can_hold:
|
||
|
can_hold.add(lb)
|
||
|
print(len(can_hold) - 1)
|
||
|
|
||
|
def count(color):
|
||
|
r = 1 # the bag itself
|
||
|
for c, icolor in bags[color]:
|
||
|
r += c * count(icolor)
|
||
|
return r
|
||
|
|
||
|
print(count("shiny gold") - 1)
|
||
|
|
||
|
|
||
|
def main():
|
||
|
data = get_data(__file__)
|
||
|
part_1(data)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|