0

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 :)

1
  • does this recursion (or loop in the case of answer) always end? Without analyzing it too deeply it seems to me that it is simple to create a tree which will cause an infinite recursion/loop (the condition check for "tree ended, no common ancestor" is missing) Commented Apr 3, 2012 at 5:12

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

For the record: this function will not find the ClosestCommonAncestor; it was just named that. I believe the OP realized this and has since edited his question.
1
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

1 Comment

I like this function, it's returning a strange error though, KeyError: ('AD', 4.0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.