fromcollectionsimportdequewithopen('input.txt','r')asf:data=deque()forlineinf:forvalinline.split(' '):data.append(int(val))classTree:def__init__(self,data):self.n_children=data.popleft()self.n_metadata=data.popleft()self.children=[Tree(data)for_inrange(self.n_children)]self.metadata=[data.popleft()for_inrange(self.n_metadata)]defget_total(self):returnsum(self.metadata)+sum(child.get_total()forchildinself.children)defget_child_value(self,child):ifchild<len(self.children):returnself.children[child].get_root_value()return0defget_root_value(self):ifnotself.children:returnsum(self.metadata)total=0foridxinself.metadata:total+=self.get_child_value(idx-1)# Index starts at 1 not 0 :(
returntotaltree=Tree(data)print(tree.get_total())print(tree.get_root_value())
Woah, that recursive constructor for Tree is really clever!
I considered building an object and then processing it after the fact, but decided to process it as I parsed it...I regretted that when I saw part 2 though 😅
I'm a Sr. Software Engineer at Flashpoint. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
Kinda happy with this one!
Woah, that recursive constructor for
Treeis really clever!I considered building an object and then processing it after the fact, but decided to process it as I parsed it...I regretted that when I saw part 2 though 😅
dequeFTW! Nice!