Skip to content

Instantly share code, notes, and snippets.

@rmuslimov
Created April 21, 2016 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmuslimov/6ca8928deaca079938be369425a4cd06 to your computer and use it in GitHub Desktop.
Save rmuslimov/6ca8928deaca079938be369425a4cd06 to your computer and use it in GitHub Desktop.
# 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