Home > front end >  Recursion python - counting vowels in a string
Recursion python - counting vowels in a string

Time:05-15

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. However, I don't understand how n increases again through recursion of the function 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.

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

CodePudding user response:

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

  • Related