How To Make This Recursive Function Iterative In Python?
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
Solution 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.
Solution 2:
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
Post a Comment for "How To Make This Recursive Function Iterative In Python?"