IndexError:String索引超出递归函数的范围

时间:2017-09-15 21:31:28

标签: python string recursion

所以我正在学习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_)

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你可以做很多事情:

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

答案 2 :(得分:1)

你可以试试这个:

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)