Python Forum

Full Version: Return boolean from recursive class method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following class which stores bit strings in a tree structure. The exists() method should return if the queried string is matched in the tree or not. However, I can't get my method return a boolean result. Can someone help?

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
    def insert(self, data):
        if self.data and data != '':
            if data[0] == '0':
                if self.left is None:
                    self.left = Node(data[0])
                self.left.insert(data[1:])
            elif data[0] == '1':
                if self.right is None:
                    self.right = Node(data[0])
                self.right.insert(data[1:])
    def exists(self, data):
        if data == '':
            print("Match")
            return True
        if data[0] == '0':
            if self.left is None:
                print("No match")
                return False
            else:
                self.left.exists(data[1:])
        elif data[0] == '1':
            if self.right is None:
                print("No match")
                return False
            else:
                self.right.exists(data[1:])

b = '1001'
r = Node('root')
r.insert(b)
r.exists(b)
r.exists('1111')
The else blocks on lines 25 and 31 don't seem to have a return. What would you expect to return if you reach those lines?
(Jul-13-2020, 04:13 AM)bowlofred Wrote: [ -> ]The else blocks on lines 25 and 31 don't seem to have a return. What would you expect to return if you reach those lines?

These are the recursive method calls
Your recursive calls don't have return statements, so those branches end up returning None.
(Jul-13-2020, 04:18 AM)ndc85430 Wrote: [ -> ]Your recursive calls don't have return statements, so those branches end up returning None.

Can you help on how to fix this?
It was implied: add return statements to those lines.
(Jul-13-2020, 04:25 AM)ndc85430 Wrote: [ -> ]It was implied: add return statements to those lines.

Got it working, thanks!