Last active
August 29, 2015 14:02
-
-
Save tomkaith13/fa2efe901a7197d7422b to your computer and use it in GitHub Desktop.
palantir question - create a tree out of tuples with 2 elements ( data, depth)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Create a tree out of a list of tuples - (data,depth) | |
Constraint: The new level node should be added to the latest of the old level node | |
ex: | |
if the tuple is: | |
(a,1) | |
(b,2) | |
(c,2) | |
(d,3) | |
(e,2) | |
(f,3) | |
the tree should look like this: | |
a | |
/ | \ | |
b c e | |
| \ | |
d f | |
''' | |
import sys | |
class Node(object): | |
def __init__(self,data,depth): | |
self.data=data | |
self.depth=depth | |
self.children = [] | |
class Tree(object): | |
def __init__(self): | |
self.root = None | |
def buildTree(self, n): | |
if self.root is None: | |
self.root = n | |
if n.depth > 1: | |
sys.exit(1) | |
return self | |
if self.root.children is None: | |
if (n.depth - 1) != self.root.depth: | |
sys.exit(1) | |
else: | |
#self.root.depth == (n.depth - 1) | |
self.root.children.append(n) | |
current_parent = self.root | |
while n.depth > current_parent.depth: | |
if n.depth == (current_parent.depth+1): | |
current_parent.children.append(n) | |
return self | |
if current_parent.children: | |
current_parent = current_parent.children[-1] | |
if n.depth == (current_parent.depth+1): | |
current_parent.children.append(n) | |
return self | |
def printTree(root): | |
if root is None: | |
print 'empty' | |
print root.depth | |
print root.data | |
print '{' | |
for i in root.children: | |
print i.data | |
print '}' | |
for i in root.children: | |
printTree(i) | |
def builder(input): | |
T = Tree() | |
for i in input: | |
print i | |
n = Node(i[0],i[1]) | |
T.buildTree(n) | |
printTree(T.root) | |
#input = [('a',1),('b',2),('c',2),('d',3),('e',2),('f',3)] | |
input = [('a',1),('b',2),('c',2),('d',3),('e',2),('f',3)] | |
builder(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment