Andre
Andre

Reputation: 1661

How to recurse without changing variables

Hello so I was wondering if there is a way to recurse through a function without changing the value of variables.

Here is my code:

def helper_list_range(self, low, high, rangelist):
    if self is EmptyValue:
        return rangelist

    else:
        if self.left is not None and self.right is not None:
            if self.root <= high and self.root >= low:
                rangelist.append(self.root)

            self.left.helper_list_range(rangelist) 
            self.right.helper_list_range(rangelist) 

            return rangelist


def list_range(self, low, high):

    rangelist = []
    self.helper_list_range(low, high, rangelist)
    return rangelist

As you can see that I am using a helper function so that I append to the rangelist without changing its value when the function does a recursion.

I was wondering is there a way I can do this without using a helper function. Using a helper function just seems a bit obscure.

Upvotes: 0

Views: 81

Answers (2)

Tsvi Tannin
Tsvi Tannin

Reputation: 407

If I were you I wouldn't use self as a parameter. It's better to pass in the root value of the tree and then work on that. I also wouldn't keep on passing in a list and then append values to it. I think it makes more sense to build up the list value through the stacked return calls.

Based on how you defined your BST I wrote up a brief solution to your problem using one function. I haven't tested it yet since I didn't have your data structure so let me know if there are any bugs.

def list_range(node, low, high):
    # base case values for each side of the tree
    lowerHalf = []
    upperHalf = []
    # You have to check each node separately since one could be not None
    # You also have to check that the subtree can even satisfy your value
    if node.left != None and node.root >= low:
        lowerHalf = list_range(node.left, low, high)
    if node.right != None and node.root <= high:
        upperHalf = list_range(node.right, low, high)
    # if the root value is in the range then we just stick it in the middle of both return values
    if low <= node.root <= high:
        return  lowerHalf + node.root + upperHalf
    # otherwise we keep stepping down
    else:
        return lowerHalf + upperHalf

Upvotes: 1

User
User

Reputation: 14853

I think you look for default arguments:

def list_range(self, low, high, rangelist = None):

    if rangelist is None:
        rangelist = []
    # here goes the code of helper_list_range

Upvotes: 2

Related Questions