【问题标题】:IndexError: String Index out of range for recursive functionIndexError:递归函数的字符串索引超出范围
【发布时间】:2018-02-25 03:04:01
【问题描述】:

所以我正在学习python并试图计算一个句子中元音的数量。我想出了如何使用 count() 函数和迭代来做到这一点,但现在我正在尝试使用递归来做到这一点。当我尝试以下方法时,我收到错误“IndexError:字符串索引超出范围”。这是我的代码。

sentence = input(": ")

def count_vowels_recursive(sentence):
    total = 0
    if sentence[0] == "a" or sentence[0] == "e" or sentence[0] == "i" or sentence[0] == "o" or sentence[0] == "u":
        total = total + 1 + count_vowels_recursive(sentence[1:])
    else:
        total = total + count_vowels_recursive(sentence[1:])   
    return the_sum

print(count_vowels_recursive(sentence))

这是我之前的两个解决方案。

def count_vowels(sentence):
    a = sentence.count("a")
    b = sentence.count("e")
    c = sentence.count("i")
    d = sentence.count("o")
    e = sentence.count("i")
    return (a+b+c+d+e)



def count_vowels_iterative(sentence):
    a_ = 0
    e_ = 0
    i_ = 0
    o_ = 0
    u_ = 0
    for i in range(len(sentence)):
        if "a" == sentence[i]:
            a_ = a_ + 1
        elif "e" == sentence[i]:
            e_ = e_ + 1
        elif "i" == sentence[i]:
            i_ = i_ + 1
        elif "o" == sentence[i]:
            o_ = o_ + 1
        elif "u" == sentence[i]:
            u_ = u_ + 1
        else:
            continue
    return (a_ + e_ + i_ + o_ + u_)

【问题讨论】:

  • 提示:当您的递归到达字符串末尾并尝试测试 sentence[0] 时会发生什么?

标签: python string recursion


【解决方案1】:

你没有基本情况。该函数将继续递归,直到sentence 为空,在这种情况下,您的第一个 if 语句将导致该索引错误。

你应该首先检查句子是否为空,如果是则返回0

【讨论】:

    【解决方案2】:

    你可以把事情缩短很多:

    def count_vowels_recursive(sentence):
        # this base case is needed to stop the recursion
        if not sentence:  
            return 0
        # otherwise, sentence[0] will raise an exception for the empty string
        return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1:])
        # the boolean expression `sentence[0] in "aeiou"` is cast to an int for the addition
    

    【讨论】:

    • 您可以进一步缩短它:return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1:])(Python 将 False 视为 0,将 True 视为 1)。
    • 没错,尽管这种强制对于初学者来说可能更加模糊。
    【解决方案3】:

    你可以试试这个:

    def count_vowels_recursive(s, count):
       if not s:
          return count
       else:
           new_count = count
           if s[0] in ["a", "e", "i", "o", "u"]:
              new_count += 1
           return count_vowels_recursive(s[1:], new_count)
    

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多