Why is my recursive function doing the desired conditionals twice?

Question:

I am trying to create a recursive function that, given a string, will return a list [consonants, vowels, other]. The problem I have is that once the base case is called and a list is returned, the function repeats one more time and gives me a list with values double of what was expected (ex: countChars("a") will return [0, 2, 0] not [0, 1, 0])
Is there something I’m missing?

     def countChars(s, list=[0, 0, 0]):
         vowels = ["a", "e", "i", "o", "u"]
         if len(s) < 1:
             return list


         if s[0] in vowels:
             list[1] += 1
         elif s[0].isalpha():
             list[0] += 1
         else:
             list[2] += 1
         return countChars(s[1:], list) 
Asked By: Brady Mitch

||

Answers:

Your issue isn’t reproducible. It’s only if you call the function more than once that it will produce incorrect results and that is because your default list argument isn’t reset unless you explicitly tell it to.

For example:

def countChars(s, lst=[0, 0, 0]):
    vowels = ["a", "e", "i", "o", "u"]
    if len(s) < 1:
        return lst


    if s[0] in vowels:
        lst[1] += 1
    elif s[0].isalpha():
        lst[0] += 1
    else:
        lst[2] += 1
    return countChars(s[1:], lst)

print(countChars('hello world'))  # [7,3,1]
print(countChars('hello world'))  # [14,6,2]
print(countChars('hello world', lst=[0,0,0]))  # [7,3,1]
Answered By: Alexander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.