Python:使用递归查看一个字符串是否是另一个字符串的旋转
Python: using recursion to see if one string is a rotation of another
我尝试了下面的代码,但它不起作用。我收到一条错误消息 "RecursionError: maximum recursion depth exceeded in comparison"。
def rot(str1, str2):
if str1 == str2:
return True
else:
for i, j in enumerate(str1):
for k, l in enumerate(str2):
if j == l:
a = str1
b = str2[k:] + str2[:k]
rot(a, b)
return False
print(rot('ab', 'ba'))
你忘了return rot(a, b)
def rot(str1, str2):
if str1 == str2:
return True
else:
for i, j in enumerate(str1):
for k, l in enumerate(str2):
if j == l:
a = str1
b = str2[k:] + str2[:k]
return rot(a, b) #returns the value of recursion
return False
print(rot('ab', 'ba'))
有一种简单但不一定显而易见的方法来检查字符串 b
是否是字符串 a
的旋转。验证长度是否匹配并且加倍 a
。如果 b
是 a + a
的子串,则有一个旋转:
def rotation(a, b):
return len(a) == len(b) and b in a + a
这值得你自己动手证明,例如,检查 hellohello
中 hello
的旋转。
至于你的代码,我不明白嵌套循环或递归是如何帮助解决问题的机制。一方面,没有基本案例,所以堆栈失败了。您需要一个索引参数来跟踪执行了多少次旋转。
一种天真的、蛮力的方法是比较 b
和 a
的每个可能的旋转,直到找到解决方案或用尽所有可能的旋转:
def rot(str1, str2):
if len(str1) == len(str2):
for i in range(len(str1)):
str2 = str2[-1] + str2[:-1]
if str2 == str1:
return True
return False
第一个解的时间复杂度是线性的,第二个解的时间复杂度是指数的。
我尝试了下面的代码,但它不起作用。我收到一条错误消息 "RecursionError: maximum recursion depth exceeded in comparison"。
def rot(str1, str2):
if str1 == str2:
return True
else:
for i, j in enumerate(str1):
for k, l in enumerate(str2):
if j == l:
a = str1
b = str2[k:] + str2[:k]
rot(a, b)
return False
print(rot('ab', 'ba'))
你忘了return rot(a, b)
def rot(str1, str2):
if str1 == str2:
return True
else:
for i, j in enumerate(str1):
for k, l in enumerate(str2):
if j == l:
a = str1
b = str2[k:] + str2[:k]
return rot(a, b) #returns the value of recursion
return False
print(rot('ab', 'ba'))
有一种简单但不一定显而易见的方法来检查字符串 b
是否是字符串 a
的旋转。验证长度是否匹配并且加倍 a
。如果 b
是 a + a
的子串,则有一个旋转:
def rotation(a, b):
return len(a) == len(b) and b in a + a
这值得你自己动手证明,例如,检查 hellohello
中 hello
的旋转。
至于你的代码,我不明白嵌套循环或递归是如何帮助解决问题的机制。一方面,没有基本案例,所以堆栈失败了。您需要一个索引参数来跟踪执行了多少次旋转。
一种天真的、蛮力的方法是比较 b
和 a
的每个可能的旋转,直到找到解决方案或用尽所有可能的旋转:
def rot(str1, str2):
if len(str1) == len(str2):
for i in range(len(str1)):
str2 = str2[-1] + str2[:-1]
if str2 == str1:
return True
return False
第一个解的时间复杂度是线性的,第二个解的时间复杂度是指数的。