索引器错误:字符串索引超出递归函数的范围

2024-09-28 17:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在学习python,并试图计算一个句子中元音的数量。我知道了如何使用count()函数和迭代来实现这一点,但现在我正尝试使用递归来实现它。当我尝试下面的方法时,我得到一个错误“IndexError:stringindex outofrange”。这是我的密码。在

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))

前两个是我的解决方案。在

^{pr2}$

Tags: or方法函数数量count错误sentence句子
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)

你可以把事情缩短一点:

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

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

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

相关问题 更多 >