Created
April 21, 2016 21:15
-
-
Save rmuslimov/6ca8928deaca079938be369425a4cd06 to your computer and use it in GitHub Desktop.
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
# coding: utf-8 | |
from itertools import dropwhile | |
input = 'nodes.txt' | |
findA = 'Node3' | |
findB = 'Node4' | |
def read_source(): | |
"Read text file." | |
with open(input) as f: | |
rows = f.read().split('\n') | |
data = {} | |
for row in filter(None, rows): | |
pair = row.split(' ', 1) | |
data[pair[0]] = pair[1] if len(pair) == 2 else None | |
return data | |
def path_for(tree, node): | |
"Get path for given node and tree." | |
path, item = [], node | |
while item is not None: | |
path.append(item) | |
item = tree[item] | |
return path | |
if __name__ == '__main__': | |
tree = read_source() | |
pathA, pathB = path_for(tree, findA), path_for(tree, findB) | |
try: | |
result = dropwhile(lambda x: x not in pathB, pathA).next() | |
except StopIteration: | |
print 'No common ancestors' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment