1

So I am struggling with writing a recursive method for finding height for a tree. This each tree node has a list of children. My code returns exception because max somehow is an empty sequence. Could someone provide a valid one?

def height(t):
    """
    Return 1 + length of longest path of t.

    @param Tree t: tree to find height of
    @rtype: int

    >>> t = Tree(13)
    >>> height(t)
    1
    >>> t = descendants_from_list(Tree(13), [0, 1, 3, 5, 7, 9, 11, 13], 3)
    >>> height(t)
    3
    """
    # 1 more edge than the maximum height of a child, except
    # what do we do if there are no children?
    if t.children is None:
        return 1

    else:
        return 1+max(height(x) for x in t.children)
1
  • 1
    Fix your indentation please : ) Commented Mar 10, 2016 at 15:37

1 Answer 1

5

I guess the t.children is an empty list - [] - on leaf nodes, not None.

>>> [] is None
False
>>> not []
True

max cannot be used with empty iterables - what do you imagine would be the maximum value in [], 0 or -∞, or 42?

Just test with if not t.children::

if not t.children:
    return 1

else:
    return 1 + max(height(x) for x in t.children)
Sign up to request clarification or add additional context in comments.

1 Comment

+1 This helped me figure out how to compute the parse tree height of a spaCy dependency parse. (Commenting here so people can maybe find this q/a by searching those terms.

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.