Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return from recursive function immediately when a solution is found

def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        class solutionFound(Exception):
            pass
        
        def dfs(s):
            if len(s) == 0:
                raise solutionFound
            
            for i in range(len(wordDict)):
                if s.startswith(wordDict[i]):
                    dfs(s[len(wordDict[i]):])
        
        try:
            dfs(s)
            return False
        except solutionFound:
            return True

In the code above, I’m making a lot of recursive calls inside the function and I just want to return immediately when a solution is found. One way to go about it is to use exception, I was just wondering if there is another way to achieve this with minimal code.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code should return True as soon as the base case is reached or False whenever the recursion finishes without any successful result. By doing this, the recursion will stop when the first result is found.

def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        
    def dfs(s):
        if len(s) == 0:
            return True
        
        for i in range(len(wordDict)):
            if s.startswith(wordDict[i]):
                if dfs(s[len(wordDict[i]):]):
                    return True

        return False
    
    return dfs(s)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading