【问题标题】:Recursive function that identifies whether string 1 is contained within string 2? (Python 3.4)识别字符串 1 是否包含在字符串 2 中的递归函数? (Python 3.4)
【发布时间】:2016-09-10 09:27:48
【问题描述】:

有没有办法编写一个递归(必需)函数,它接受两个字符串作为参数,如果第一个字符串中的所有字符都可以按顺序在第二个字符串中找到,则返回 True;否则为 False?

例如:

>>> contains("lit", "litter")
True
>>> contains("thot", "thurtle")
False
>>> contains("ratchet", "ramtbunchiousest")
True
>>> contains("shade", "hadsazie")
False

字母不需要连续(如第三个示例),但它们必须按顺序排列(这就是第四个示例失败的原因)。

我写了这段代码:

def contains_recursive(s1, s2):

if s1 == "":
    return True
elif s1[0] == s2[0]:
    return contains_recursive(s1[1:], s2[1:])
elif s1[0] != s2[0]:
    return contains_recursive(s1[0], s2[1:])
else:
    return False

return contains_recursive(s1, s2) == True

它给出了这个错误:

IndexError: string index out of range

我应该怎么做才能解决这个问题?

【问题讨论】:

  • 为什么需要递归?学习清酒、作业,还是……?
  • @croesus 无需递归,您可以使用“in”运算符 ex: result_bool = substring in string
  • @AnjaneyuluBatta - 除非字符是连续的,否则将返回 False
  • 问题似乎在这里:elif s1[0] != s2[0]: return contains_recursive(s1[0], s2[1:])。当s1[0] != s2[0]时,它会递归调用自己,将s2[1:]传递给contains_recursive。当它运行到s2 的长度为1 时,它会抛出错误,因为s2[1:] 超出范围。

标签: python string recursion


【解决方案1】:

我认为 递归 是一项要求。在这种情况下:

def contains(s1, s2):
    if not s1:
        return True
    i = s2.find(s1[0])
    if i == -1:
        return False
    else:
        return contains(s1[1:], s2[i+1:])

这会产生:

>>> contains("lit", "litter")
True
>>> contains("thot", "thurtle")
False
>>> contains("ratchet", "ramtbunchiousest")
True
>>> contains("shade", "hadsazie")
False

【讨论】:

    【解决方案2】:

    避免使用递归函数来提高效率。

    def test(s1, s2):
        idx2 = 0
        for c in s1:
            if c in s2[idx2:]:
                idx2 = s2.index(c) + 1
            else:
                return False
    
        return True
    
    # Test
    lists = [   ("lit", "litter"), 
                ("thot", "thurtle"), 
                ("ratchet", "ramtbunchiousest"), 
                ("shade", "hadsazie")]
    
    result = [test(*t) for t in lists]
    print(result)
    # Output
    [True, False, True, False]
    

    【讨论】:

      【解决方案3】:

      您遇到的错误可能是因为 s2 是一个空字符串。还要检查它的长度。如果您达到这一点,则意味着您尚未找到要搜索的所有字母,因此最终结果应该是错误的。

      if s2 == '':
          return False
      

      【讨论】:

        【解决方案4】:

        在线:

         return contains_recursive(s1[0], s2[1:])
        

        您将 s1 缩短为一个字符,但在下一次通话时您可能会点击:

         return contains_recursive(s1[1:], s2[1:])
        

        用 s1 一串 len 1。

        你需要使用:

        return contains_recursive(s1, s2[1:])
        

        并添加对 s1 长度的检查

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-26
          • 2021-12-18
          • 2021-02-09
          • 1970-01-01
          • 2013-03-15
          • 2010-10-28
          • 1970-01-01
          相关资源
          最近更新 更多