Question

I'm working on a recursive function which is meant to return (not print) the number of alphabetical characters in a string. I understand it's very easy to do this by iteration, but my goal is to do it recursively. The function I have written executes properly the first time it's called, but I can't find a way to reset the counter before the next execution. Here's what I have:

counter = 0
def recAlphaCount(s):
    global counter

    if len(s) == 0:
        return 0 
    else:
        if s[0].isalpha():
            counter += 1

        recAlphaCount(s[1:])
        return counter

I've tried assigning the value of counter to another variable and resetting the counter but I can't manage to extract its value and still have it reset.

Is there a way to write this recursively without using a global counter? Or is there a way to return the counter and reset it within the function?

Thanks

Was it helpful?

Solution

You can maintain the count in the parameter itself, like this

def recAlphaCount(s, counter = 0):
    if len(s):
        counter = recAlphaCount(s[1:], counter + int(s[0].isalpha()))
    return counter

This can also be solved like this, without explicitly maintaining the count.

def recAlphaCount(s):
    if len(s) == 0:
        return 0
    elif s[0].isalpha():
        return 1 + recAlphaCount(s[1:])
    else:
        return recAlphaCount(s[1:])

This can be shortened to

def recAlphaCount(s):
    if len(s) == 0:
        return 0
    return int(s[0].isalpha()) + recAlphaCount(s[1:])

OTHER TIPS

global variables are rarely the right answer! You could make counter an argument defaulting to zero and refactor slightly:

def recAlphaCount(s, counter=0):
    if len(s) == 0:
        return counter
    else:
        if s[0].isalpha():
            counter += 1
        return recAlphaCount(s[1:], counter)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top