【问题标题】:First index appearance in a string recursive字符串递归中的第一个索引出现
【发布时间】:2014-04-18 05:15:09
【问题描述】:

我正在尝试编写一个递归函数,该函数将字符串和字符作为输入。该函数返回字符串中字符的第一个索引外观。如果字符未出现,则返回无。 我只有返回 None 才有问题。在我的情况下,当字符串中没有字符时,函数会抛出错误,有什么建议吗?

def char_first_index(s,c):
    if len_rec(s)==0:
        return None
    if s[0]==c:
        return  0
    return 1+ char_first_index(s[1:],c)

【问题讨论】:

  • 那个错误是...?另外,len_rec 是什么?
  • TypeError: +: 'int' and 'NoneType' 的操作数类型不受支持
  • 这是因为只有最后一次调用,即空字符串上的调用,才会返回None。但是之前的所有调用都返回 1 + 一些东西。这会产生诸如1 + 1 + 1 + ... + None 之类的东西。而且您不能将None 添加到整数。恐怕您需要重新设计该功能。如果字符在字符串中,如何返回-float("Infinity"),这样用户可以检查值是否为< 0,或者返回1,并要求用户检查结果是否大于字符串的长度。总是返回相同类型的对象通常是个好主意。

标签: python python-3.x recursion


【解决方案1】:

您在每次迭代中创建一个新切片,并且每次递归都必须加 1。相反,在索引上递归:

def char_first_index(s, c, index = 0):
    if len(s) == index:
        return None
    if s[index] == c:
        return index
    return char_first_index(s, c, index + 1)

【讨论】:

    【解决方案2】:

    如果字符不在输入中,您的函数会尝试执行1+None,因此会出现错误。试试这个:

    def char_first_index(s,c):
        if len_rec(s)==0:
            return None
        if s[0]==c:
            return  0
        answer =  char_first_index(s[1:],c)
        if answer is not None:
            return 1+answer
        else:
            return answer
    

    【讨论】:

      【解决方案3】:

      首先我假设len_rec 是一个获取字符串长度的递归函数;你还没有写,所以我把它改成len()进行测试。

      其次,我不确定该函数应该如何处理不在字符串中的字符,因为这意味着尝试将None 添加到数字中。

      这是一个修改后的函数,它仍然使用您的计数想法,但处理返回 None 的情况:

      def char_first_index(s,c):
          if len(s)==0:
              return None
          elif s[0]==c:
              return 0
          else:
              count = char_first_index(s[1:], c)
              if count != None:
                  return count + 1
              else:
                  return None
      

      【讨论】:

        猜你喜欢
        • 2013-05-27
        • 1970-01-01
        • 2012-09-19
        • 2021-06-18
        • 2021-07-12
        • 1970-01-01
        • 2016-05-20
        • 2023-04-04
        • 2021-07-29
        相关资源
        最近更新 更多