Python 索引器:字符串索引超出递归函数的范围
因此,我正在学习python,并试图计算一个句子中元音的数量。我已经知道如何使用count()函数和迭代来实现它,但现在我正尝试使用递归来实现它。当我尝试以下方法时,我得到一个错误“IndexError:字符串索引超出范围”。这是我的密码Python 索引器:字符串索引超出递归函数的范围,python,string,recursion,Python,String,Recursion,因此,我正在学习python,并试图计算一个句子中元音的数量。我已经知道如何使用count()函数和迭代来实现它,但现在我正尝试使用递归来实现它。当我尝试以下方法时,我得到一个错误“IndexError:字符串索引超出范围”。这是我的密码 sentence = input(": ") def count_vowels_recursive(sentence): total = 0 if sentence[0] == "a" or sentence[0] == "e" or sen
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_)
你没有基本的理由。函数将一直递归,直到
语句
为空,在这种情况下,第一个if语句将导致该索引错误
您应该首先检查句子是否为空,如果为空,则返回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
您可以尝试以下方法:
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)
提示:当递归到达字符串末尾时,您尝试测试
语句[0]
?您可以进一步缩短它:return(在“aeiou”中的句子[0])+count\u元音\u recursive(句子[1:])
(Python将False计为0,将True计为1)。True,尽管这种强制对初学者来说可能更加模糊。