如何使用递归函数 return "true" or false?
how to return "true" or false using recursive function?
这是我的代码:
def mirror(s,s2):
new=""
if s=="":
return s
new = mirror(s[1:],s2) +s[0]
if len(new)==len(s2):
if new==s2:
return True
else:
return False
def main():
print(mirror("dcba","abcd"))
main()
如果像下面这样构建递归函数,您应该会取得一些成功。
recurs() {
if (finalCondition) return true
if (isReflection) {
return recurs()
}
else {
return false
}
}
想法是递归遍历字符串,首先检查结束条件。这可能是一个空字符串或类似的东西。然后检查反射条件是否仍然成立。如果是,则继续递归,否则 return false
。当您 return false
时,它将一直传播到初始调用。同样,如果您达到结束条件,并且 return 为真,这意味着您查看了整个字符串并且它们满足反射要求并且 true
将传播。
刚接触递归的程序员往往会使问题变得比必要的更难,并且不相信递归会为他们完成工作。为了使这个问题在递归方面有意义,您需要检查每个字符串中的一个字符,然后决定将它们声明为不同的,或者递归执行相同的操作直到 运行 超出字符(基本情况)。类似于:
def mirror(s1, s2):
if not s1 or not s2: # base case
return not s1 and not s2 # if both empty, success!
if s1[0] != s2[-1]: # compare opposite ends
return False
return mirror(s1[1:], s2[:-1]) # recurse on remaining strings
这是我的代码:
def mirror(s,s2):
new=""
if s=="":
return s
new = mirror(s[1:],s2) +s[0]
if len(new)==len(s2):
if new==s2:
return True
else:
return False
def main():
print(mirror("dcba","abcd"))
main()
如果像下面这样构建递归函数,您应该会取得一些成功。
recurs() {
if (finalCondition) return true
if (isReflection) {
return recurs()
}
else {
return false
}
}
想法是递归遍历字符串,首先检查结束条件。这可能是一个空字符串或类似的东西。然后检查反射条件是否仍然成立。如果是,则继续递归,否则 return false
。当您 return false
时,它将一直传播到初始调用。同样,如果您达到结束条件,并且 return 为真,这意味着您查看了整个字符串并且它们满足反射要求并且 true
将传播。
刚接触递归的程序员往往会使问题变得比必要的更难,并且不相信递归会为他们完成工作。为了使这个问题在递归方面有意义,您需要检查每个字符串中的一个字符,然后决定将它们声明为不同的,或者递归执行相同的操作直到 运行 超出字符(基本情况)。类似于:
def mirror(s1, s2):
if not s1 or not s2: # base case
return not s1 and not s2 # if both empty, success!
if s1[0] != s2[-1]: # compare opposite ends
return False
return mirror(s1[1:], s2[:-1]) # recurse on remaining strings