2017-09-15 71 views
1

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

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_) 
+0

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

回答

1

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

你应该先if语句是空的,所有的检查,如果这样返回0

0

可以缩短事情颇有几分:

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 
+0

你可以缩短它更多:'返回(aeiou“中的句子[0])+ count_vowels_recursive(句子[1:])'(Python将False计为0,True计为1)。 –

+0

确实如此,即使这种胁迫对初学者来说可能更加模糊。 – schwobaseggl

0

你可以试试这个:

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)