Created
March 3, 2016 22:58
-
-
Save shklqm/fa7e5184ca3874e8cc16 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/bin/python | |
def rem(keyToBeSearched, tree): | |
# print "calling" | |
for key,val in tree.items(): | |
if key == keyToBeSearched: | |
# print "found", keyToBeSearched | |
tree.pop(key, None) | |
global branch | |
branch = val | |
return True | |
else: | |
rem(keyToBeSearched,val) | |
def insert(n1,n2,tree,orginalTree): | |
global branch | |
if n2 in tree: | |
# print "inserted1",n1,n2 | |
d1 = {n1:{}} | |
rem(n1,orginalTree) | |
# global branch | |
if branch != None and len(branch): | |
d1 = branch | |
branch = None | |
tree[n2] = dict(tree[n2].items() + d1.items()) | |
return True | |
elif n1 in tree: | |
# print "inserted2" | |
d1 = {n2:{}} | |
rem(n2,orginalTree) | |
# global branch | |
if branch != None and len(branch): | |
d1 = branch | |
branch = None | |
tree[n1] = dict(tree[n1].items() + d1.items()) | |
return True | |
else: | |
for key,val in tree.items(): | |
if insert(n1,n2,val,orginalTree): | |
return True | |
return False | |
def countValues(key,count,tree): | |
print "\'"+key+"\'", count | |
for key,val in tree.items(): | |
countValues(key,count + len(tree),val) | |
# print "count: ",count, " tree: ",tree | |
return count | |
tree = {} | |
branch = None | |
t = int(raw_input().strip()) | |
for a0 in xrange(t): | |
n1, n2 = raw_input().strip().split(' ') | |
if not (insert(n1,n2,tree,tree)): | |
d1 = {n1:{}} | |
d2 = {n2:d1} | |
tree = dict(tree.items() + d2.items()) | |
# print "--->",tree | |
print "-----------------------" | |
print tree | |
# print countValues('',0,tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment