Search code examples
pythonrecursionrecursive-backtracking

Recursive Backtracking no return value python


Full problem is on https://www.hackerrank.com/challenges/password-cracker/ I would like to know whats wrong with my recursive backtracking implementation

Problem: Given an array of passwords, return "Wrong password" if word is not a combination of those passwords

I'd please like to ask how can I return a value from this; I'm able to print the solution but not return it in a string. I'm not sure what can I do from here; I tried returning a value when word == '' but that didnt work

def crackhelper(passwords,word,sol):
    #Check if theres some password that currently works
    print(sol)
    for password in passwords:
        if word[:len(password)]==password:
            sol+=password
            crackhelper(passwords,word[len(password):],sol)
            sol=sol[:-len(password)]

    return ''
def crack():
    word="wedowhatwemustbecausewecane"
    passwords="because can do must we what cane".split(' ')
    j=crackhelper(passwords,word,'')    
    print(j)
    #print(passwords)

Solution

  • def crack_helper(passwords, word, sol):
        # Check if there is some password that currently works.
        if word ==  "":
            return sol
        for password in passwords:
            if word[:len(password)] == password:
                sol += password
                s = crack_helper(passwords, word[len(password):], sol)
                if s != "No Result":
                    sol = s
                    return sol
                sol = sol[:-len(password)]
        return "No Result"
    

    This should do that job :)