Louis
Louis

Reputation: 23

IndexError: String Index out of range for recursive function

So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code.

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

Here are my previous two solutions.

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

Upvotes: 2

Views: 774

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

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)

Upvotes: 1

user2390182
user2390182

Reputation: 73460

You can shorten things up quite a bit:

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

You have no base case. The function will keep recursing until sentence is empty, in which case your first if statement will cause that index error.

You should first of all check if sentence is empty, and if so return 0

Upvotes: 2

Related Questions