0

I am to implement a length method for a custom Phylogenetic Tree class so we can call len(TreeObject) on it. The length of a tree is defined by how many leafs it has. A leaf means that node has no children. 'self.children' is equal to a list of tuples (node, weight) of that nodes children. I am very close I believe:

 def __len__(self):

# everytime it reaches the base case I should add 1
    if self.isLeaf():
        print('base case - reached leaf!')
        return 1

    for t,w in self.children:  
        print('not leaf so sent through loop')
        numLeaves = len(t)

    return numLeaves

The code is reaching the if statement the correct number of times, e.g. if the length is 3 it outputs 'base case - reached leaf!' 3 separate times. I just need a way of adding those together and storing it in a variable.

1 Answer 1

2

Very close indeed. You are just overwriting numLeaves instead of summing them:

numLeaves = 0
for t,w in self.children:  
    print('not leaf so sent through loop')
    numLeaves += len(t)

It can also be implemented differently:

sum(len(t) for (t,w) in self.children)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much. idk how I didn't see that sooner. also I appreciate the more elegant python bit, thanks.

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.