Sly Cooper
Sly Cooper

Reputation: 79

Return statement not executing

Hey guys so i have a problem and it is that my return statement is not executing. This is my sudo code. It searches a tree to see if an item is in the tree.

def search(self, i):
    if left child is None and right child is None
        if self.data == i:
            return True
        else:
            pass 
    elif self.data == i:
        return True
    else:
        if left child exists:
            return self.left.search(i)
        if right child exists:
            return self.right.search(i)

The code seems to work except when self.data == i, the code does not run the return True statement even though the if statement is executed. Does anyone know why this is? Thanks in advance!

EDIT: ADDED THE SELF PARAMETER. IT WAS SUPPOSED TO BE THERE, WAS A TYPO..

I inserted the numbers 3, 8, 2 and 1 into the tree and then searched for 1. I added a print statement if left child is None and right child is None: if self.data == i: print('self.data == i') return True I added that print statement when searching for 1 and the print statement did print which means that the if statement was executed, however, the return True statement does not execute

Upvotes: 0

Views: 161

Answers (1)

Sergiu Toarca
Sergiu Toarca

Reputation: 2749

I imagine you're trying to do a binary search, in which case you have some problems in your code. The return statement is probably not executed because the condition self.data == i fails. Also, note that if the root has a left child, the right child never gets looked at in your original code.

This is an implementation of a linear search, I'll leave it as an exercise to modify it to a binary search.

def search(self, i):
    if self.data == i:
        return True

    if self.left is not None:
        if self.left.search(i):
            return True
    if self.right is not None:
        return self.right.search(i)
    return False

Upvotes: 2

Related Questions