add solution 7, parts 1 and 2

This commit is contained in:
randomuser 2021-07-20 12:55:49 -05:00
parent b616d265a2
commit c273962081
4 changed files with 76 additions and 0 deletions

Binary file not shown.

15
2020/7/paste Normal file
View File

@ -0,0 +1,15 @@
File "/home/usr/git/adventofcode/2020/7/solution.py", line 52, in <module>
print(bagconfigurations(rules, Bag('shiny gold')))
File "/home/usr/git/adventofcode/2020/7/solution.py", line 42, in bagconfigurations
cnt += bagconfigurations(rules, i.bagspec())
File "/home/usr/git/adventofcode/2020/7/solution.py", line 42, in bagconfigurations
cnt += bagconfigurations(rules, i.bagspec())
File "/home/usr/git/adventofcode/2020/7/solution.py", line 42, in bagconfigurations
cnt += bagconfigurations(rules, i.bagspec())
[Previous line repeated 994 more times]
File "/home/usr/git/adventofcode/2020/7/solution.py", line 40, in bagconfigurations
if i.cancontain(bag): cnt += 1
File "/home/usr/git/adventofcode/2020/7/solution.py", line 27, in cancontain
if not i.color == bag.color: continue
RecursionError: maximum recursion depth exceeded in comparison

9
2020/7/sample_input Normal file
View File

@ -0,0 +1,9 @@
light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.

52
2020/7/solution.py Normal file
View File

@ -0,0 +1,52 @@
#!/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')))