【问题标题】:Recursive Backtracking no return value python递归回溯没有返回值python
【发布时间】:2020-08-16 15:06:03
【问题描述】:

完整问题在https://www.hackerrank.com/challenges/password-cracker/ 我想知道我的递归回溯实现有什么问题

问题:给定一个密码数组,如果 word 不是这些密码的组合,则返回“错误密码”

我想问一下如何从这里返回一个值;我可以打印解决方案,但不能以字符串形式返回。我不确定我能从这里做什么;我尝试在 word == '' 时返回一个值,但这没有用

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)

【问题讨论】:

标签: python recursion recursive-backtracking


【解决方案1】:
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"

这应该可以完成这项工作:)

【讨论】: