递归回溯无 return 值 python
Recursive Backtracking no return value python
完整问题在 https://www.hackerrank.com/challenges/password-cracker/
我想知道我的递归回溯实现有什么问题
问题:给定一组密码,return如果单词不是这些密码的组合,则“密码错误”
我想问一下如何 return 从中得到一个值;我可以打印解决方案,但不能 return 打印成字符串。我不确定我能从这里做什么;我尝试 returning 一个值 when 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)
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"
这应该可以完成这项工作:)
完整问题在 https://www.hackerrank.com/challenges/password-cracker/ 我想知道我的递归回溯实现有什么问题
问题:给定一组密码,return如果单词不是这些密码的组合,则“密码错误”
我想问一下如何 return 从中得到一个值;我可以打印解决方案,但不能 return 打印成字符串。我不确定我能从这里做什么;我尝试 returning 一个值 when 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)
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"
这应该可以完成这项工作:)