Reputation: 1693
Usually I'm good with this type of thing, but this is bugging me. I had to write this function last week, and writing it recursively made the most sense, although now I'm trying to find a way to make it iterative to incorporate it into another function I'm writing. This is the recursive version of the function,
def XXX (x,y,z):
if z[x][0][0] != z[y][0][0]:
XXX(z[x][0],z[y][0],z)
else:
return z[x][0]
and this is the data structure
{'A': [('AD', 4.0), None, None], 'C': [('ADBFGC', 14.5), None, None], 'B': [('BF', 0.5), None, None], 'E': [('ADBFGCE', 17.0), None, None], 'D': [('AD', 4.0), None, None], 'G': [('BFG', 6.25), None, None], 'F': [('BF', 0.5), None, None], 'ADBFG': [('ADBFGC', 6.25), ('AD', 4.25), ('BFG', 2.0)], 'BF': [('BFG', 5.75), ('B', 0.5), ('F', 0.5)], 'ADBFGC': [('ADBFGCE', 2.5), ('ADBFG', 6.25), ('C', 14.5)], 'ADBFGCE': [None, ('ADBFGC', 2.5), ('E', 17.0)], 'BFG': [('ADBFG', 2.0), ('BF', 5.75), ('G', 6.25)], 'AD': [('ADBFG', 4.25), ('A', 4.0), ('D', 4.0)]}
I'm completely blanking on this, any help would be appreciated :)
Upvotes: 0
Views: 603
Reputation: 226326
def ClosestCommonAncestor (otu1,otu2,tree):
while True:
a = tree[otu1][0]
b = tree[otu2][0]
if a[0] == b[0]:
return a
otu1 = a
otu2 = b
Upvotes: 1
Reputation: 91092
def ClosestCommonAncestor(otu1, otu2, tree):
while tree[otu1][0][0] != tree[otu2][0][0]:
otu1,otu2,tree = tree[otu1][0],tree[otu2][0],tree
return tree[otu1][0]
Do note that it should be possible to add functionality to the recursive version. I would also suggest defining a Tree(*children)
class to make things clearer.
Upvotes: 1