[英]Recursion python - counting vowels in a string
以下代码来自 geeks for geeks - 链接当我在 pythontutor.com 上逐行可视化代码时,我了解到通过递归 countVowels() 函数将 n 减为 1。 但是,我不明白 n 如何通过函数 isVowel() 的递归再次增加。
P2 - 我也不明白为什么 pythontutor 上的第 27 步回到 isVowel() 并在 n = 1 时已经执行该行时将 n 增加到 2。我的意思是它应该直接转到下一个返回函数(return(countVowels(str, n-1) + isVowel(str[n-1]))
请帮帮我。
def isVowel(ch):
return ch.upper() in ['A', 'E', 'I', 'O', 'U']
#count no of vowels from 0 to n
def countVowels(str, n):
if(n==1):
return isVowel(str[n-1])
return(countVowels(str, n-1) + isVowel(str[n-1]))
str = 'abc de'
print(str[0])
print(countVowels(str, len(str)))
看看如何评估这些函数:
countVowels("abc", 3) = countVowels("abc", 2) + isVowel("abc"[2])
= (countVowels("abc", 1) + isVowel("abc"[1])) + isVowel("abc"[2])
= ((isVowel("abc"[0])) + isVowel("abc"[1])) + isVowel("abc"[2])
= ((True) + False) + False
= 1
必须首先解决对countVowels
的递归调用,然后再isVowel()
,因为 Python 从左到右,从内到外计算表达式(就像嵌套表达式一样(x + 1)**2
,例如)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.