Skip to content

Instantly share code, notes, and snippets.

@pta2002
Created December 7, 2017 23:36
Show Gist options
  • Save pta2002/c3033811b92cecfdc5ec308e1dc9de15 to your computer and use it in GitHub Desktop.
Save pta2002/c3033811b92cecfdc5ec308e1dc9de15 to your computer and use it in GitHub Desktop.
import time
class Node(object):
def __init__(self, name, weight, children):
self.name = name
self.weight = weight
self.children = children
def __str__(self):
return self.name + " " + str(self.children)
def getWeight(self):
m = 0
for c in self.children:
m += c.getWeight()
return m + self.weight
def parse(content):
queue = {}
for l in content.split('\n'):
if l.strip() != '':
words = l.split(' ')
name = words[0]
weight = int(words[1][1:-1])
children = []
if len(words[2:]) > 0:
while len(words[2:]) > 1:
w = words.pop()
if w.endswith(','):
w = w[:-1]
children.append(w)
queue[name] = [Node(name, weight, []), children]
return queue
with open('d6in.txt') as f:
queue = parse(f.read())
def makeNode(node):
c = queue[node][1]
r = queue[node][0]
for n in c:
child = makeNode(n)
del queue[n]
r.children.append(child)
queue[node][1] = []
return r
i = 0
while len(queue) > 1:
k = list(queue.keys())[i]
queue[k][0] = makeNode(k)
i = (i + 1) % len(queue)
def findWrongWeight(node):
l = []
for n in node.children:
l.append(n.getWeight())
counts = {}
for i in l:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
print(counts, node.weight)
if len(counts) > 1:
m = min(counts, key=counts.get)
n = node.children[l.index(m)]
findWrongWeight(n)
node = queue[list(queue.keys())[0]][0]
findWrongWeight(node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment