Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution to advent of code - Day 12 - Part 2
#aoc_d12.py
import re
inp = open('input_d12.txt','r').readlines()
#inp = ["0 <-> 2","1 <-> 1", "2 <-> 0, 3, 4", "3 <-> 2, 4", "4 <-> 2, 3, 6", "5 <-> 6", "6 <-> 4, 5"]
count = 0
connections = {}
visited = []
groups = [None]*len(inp)
def check(items):
#print 'itms:',items#, groups
if items in groups:
return items
# #print 'yup'
# return items
if type(items) is int and items not in visited:
#print 'loop for ',items,visited
visited.append(items)
r = check(connections[items])
#visited.remove(items)
#print 'loop result:',r
return r
elif type(items) is int and items in visited:
#print '=> ',items, visited
return items
#print 'moar check'
w = []
for i in items:
#print 'loop for ',i,visited
r = check(i)
if type(r) is int:
w.append(r)
#print set(w)
#print '=> f2'
return next(iter(set(w)))
for i in inp:
if "," in i:
m = re.match("(\d+)\s<->\s([0-9,\s]+)",i)
#print i
i1 = int(m.group(1))
#print m.group(2)
items = [int(e) for e in m.group(2).split(',')]
connections[i1] = items
#for it in items:
# connections[it] = i1
if "," not in i:
m = re.match("(\d+)\s<->\s(\d+)",i)
i1 = int(m.group(1))
i2 = int(m.group(2))
if i1 in connections:
connections[i1].append(i2)
else:
connections[i1] = [i2]
if i2 in connections:
connections[i2].append(i1)
else:
connections[i2] = [i1]
for k in connections:
visited = []
#if connections[k] is int and connections[k] == k:
#print "+1 for k=",k
# groups[k] = +1
#else:
#print k
visited.append(k)
r = check(connections[k])
if type(r) is int:
#print "k",k,"ended up in:",r
groups[k] = r
else:
pass#print "no for k=",k
#print '-----'
#print groups
print set(groups)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment