所以我在学习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}$
你可以试试这个:
你可以把事情缩短一点:
你没有基本情况。函数将一直递归,直到
sentence
为空,在这种情况下,第一个if语句将导致索引错误。在首先应该检查句子是否为空,如果是空的,则返回0
相关问题 更多 >
编程相关推荐