问题描述
完整的问题在https://www.hackerrank.com/challenges/password-cracker/上 我想知道我的递归回溯实现有什么问题
问题:给定一组密码,如果单词不是这些密码的组合,则返回“错误密码”
我想问一下如何从中返回一个值;我可以打印解决方案,但不能以字符串形式返回。我不确定从这里可以做什么。我尝试在单词==''时返回一个值,但这没用
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,'')
print(j)
#print(passwords)
解决方法
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"
这应该可以完成:)