advent/2020/7/solution.py

53 lines
1.4 KiB
Python
Raw Permalink Normal View History

2021-07-20 12:55:49 -05:00
#!/usr/bin/env python
class Bag:
def __init__(self, line):
split = line.split(' ')
if split[0].isalpha():
self.adj = split[0]
self.color = split[1]
else:
self.adj = split[1]
self.color = split[2]
def __str__(self):
return "{} {} bag".format(self.adj, self.color)
class Rule:
def __init__(self, line):
contain = line.split(' contain ')
self.bag = Bag(contain[0])
if contain[1] != 'no other bags':
requires = contain[1].split(', ')
self.requires = []
for i in requires:
self.requires.append(Bag(i))
else: self.requires = []
def cancontain(self, bag):
cnt = 0
for i in self.requires:
if not i.color == bag.color: continue
if not i.adj == bag.adj: continue
cnt += 1
if cnt > 0: return True
return False
def bagspec(self):
return self.bag
def pseudoremove(list, pos):
return list[0:pos - 1] + list[pos + 1:]
def bagconfigurations(rules, bag):
cnt = 0
for i in rules:
if i.cancontain(bag): cnt += 1
for j in rules:
if j.cancontain(i.bagspec()): cnt += 1
return cnt
fd = open('sample_input', 'r')
lines = [i.rstrip() for i in fd.readlines()]
rules = []
for i in lines:
rules.append(Rule(i))
print(bagconfigurations(rules, Bag('shiny gold')))