Home > Software engineering >  Error when using a variable in recursion to iterate through a binary tree (Python)
Error when using a variable in recursion to iterate through a binary tree (Python)

Time:08-12

def berry_finder(t):
    """Returns True if t contains a node with the value 'berry' and 
    False otherwise.

    >>> scrat = tree('berry')
    >>> berry_finder(scrat)
    True
    >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('berry')]), tree('branch2')])
    >>> berry_finder(sproul)
    True
    """
    if is_leaf(t):
        if label(t)=='berry':
            return True
        else :
            return False    
    else:
        if label(t)=='berry':
            return True
        else:
            for branch in branches(t):
                branch_list=[]
                branch_list =[berry_finder(branch)]                         
            if True in branch_list:
                return True
            else:
                return False

This is the wrong code I wrote.And the function's purpose is to find if any node's value is 'berry'.

The wrong part of the code is the recursion part(i.e. the code under the second else)

But I think my solution is right.I create a branch_list to store all boolean value of the branches,and if any value in branch_list is True ,then return True.

I wonder whethet it is the problem of the using of branch_list,because the branch_list may change during the different depth of recursion?

CodePudding user response:

The problem is that you reset branch_list in each iteration of the loop, so losing the previous boolean results, and ending up with only the last result.

You need to move that out of the loop, like so:

        branch_list=[]
        for branch in branches(t):
            branch_list =[berry_finder(branch)]

Not a problem, but it is more natural to use append here:

        branch_list=[]
        for branch in branches(t):
            branch_list.append(berry_finder(branch))

And more pythonic is to build the list in one go through map:

        branch_list = list(map(berry_finder, branches(t)))

or comprehension:

        branch_list = [berry_finder(branch) for branch in branches(t)]
  • Related