Python Forum
Return boolean from recursive class method - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Return boolean from recursive class method (/thread-28294.html)



Return boolean from recursive class method - medatib531 - Jul-13-2020

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')



RE: Return boolean from recursive class method - bowlofred - Jul-13-2020

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?


RE: Return boolean from recursive class method - medatib531 - Jul-13-2020

(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


RE: Return boolean from recursive class method - ndc85430 - Jul-13-2020

Your recursive calls don't have return statements, so those branches end up returning None.


RE: Return boolean from recursive class method - medatib531 - Jul-13-2020

(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?


RE: Return boolean from recursive class method - ndc85430 - Jul-13-2020

It was implied: add return statements to those lines.


RE: Return boolean from recursive class method - medatib531 - Jul-13-2020

(Jul-13-2020, 04:25 AM)ndc85430 Wrote: It was implied: add return statements to those lines.

Got it working, thanks!