简体   繁体   English

递归python - 计算字符串中的元音

[英]Recursion python - counting vowels in a string

The following code is from geeks for geeks - link When I executed to visualize the code line by line on pythontutor.com, I understand that n is being reduced to 1 by recursing the countVowels() function.以下代码来自 geeks for geeks - 链接当我在 pythontutor.com 上逐行可视化代码时,我了解到通过递归 countVowels() 函数将 n 减为 1。 However, I don't understand how n increases again through recursion of the function isVowel().但是,我不明白 n 如何通过函数 isVowel() 的递归再次增加。

P2 - I also don't understand why step 27 on pythontutor goes back to isVowel() and increases n to 2 when that line has already been executed for n = 1. I mean it should go to the next return function directly (return(countVowels(str, n-1) + isVowel(str[n-1])) Please help me out. 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))) 

Take a look at how these functions are evaluated:看看如何评估这些函数:

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

The recursive calls to countVowels must be resolved first, before isVowel() is ever evaluated, because Python evaluates expressions from left to right, and from inside to outside (like in the case of nested expressions like (x + 1)**2 , for example).必须首先解决对countVowels的递归调用,然后再isVowel() ,因为 Python 从左到右,从内到外计算表达式(就像嵌套表达式一样(x + 1)**2 ,例如)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM