1

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) 
  • Consider using a different identifier for your `list` variable, as `list` is a reserved word in Python and represents the `list` type. – h0r53 Oct 03 '22 at 19:13
  • How many times are you calling `countChars` from the top level? `list` is not reset to `[0, 0, 0]` the second time you call it from the top level. – Fiddling Bits Oct 03 '22 at 19:14
  • 1
    @FiddlingBits Thank you! That was the problem, the function was called twice in my test file and each call used the default list values, but I changed it to use arguments instead and it now works fine. – Brady Mitch Oct 03 '22 at 19:23

1 Answers1

2

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]
Alexander
  • 16,091
  • 5
  • 13
  • 29