【问题标题】:Python: using recursion to see if one string is a rotation of anotherPython:使用递归来查看一个字符串是否是另一个字符串的旋转
【发布时间】:2019-03-23 22:02:46
【问题描述】:

我尝试了下面的代码,但它不起作用。我收到一条错误消息“RecursionError:比较中超出了最大递归深度”。

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'))

【问题讨论】:

  • “旋转”是什么意思?逆转?我说“你好”的唯一轮换是“olleh”是否正确?
  • 旋转将是一个从另一个字符开始的字符串,但其他字符的顺序相同。对于“hello”,轮换包括“elloh”、“llohe”、“lohel”和“ohell”。

标签: python string recursion rotation


【解决方案1】:

有一种简单但不一定明显的方法来检查字符串b 是否是字符串a 的旋转。验证长度是否匹配并将a 加倍。如果ba + a 的子字符串,则您有一个轮换:

def rotation(a, b):
    return len(a) == len(b) and b in a + a

这值得自己亲手证明,例如,检查hellohellohello 中的旋转。


至于您的代码,我不理解嵌套循环或递归是如何有助于解决问题的机制。一方面,没有基本情况,所以堆栈崩溃了。您需要一个 index 参数来跟踪已执行的旋转次数。

一种天真的蛮力方法是将ba 的每个可能的轮换进行比较,直到您找到解决方案或用尽所有可能的轮换:

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

第一个解的时间复杂度是线性的,第二个解是指数的。

Try it!

【讨论】:

    【解决方案2】:

    你忘了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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 2019-05-11
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多