1

how can I use recursion to find the amount of 'a' that is in a string:

example: get_a('halloa') -> 2

here is what I have:

    def get_a(string):
        '''
        return how many times a exist in the string using recursion
        '''
        if string == '':
            return 0
        if string[0] == 'a':
            return 1
    return get_a(string[1:])
3
  • 2
    Do you really have to use recursion for this? Commented Feb 8, 2018 at 15:19
  • 1
    @PM2Ring: Maybe it's an exercise in functional-style programming. Commented Feb 8, 2018 at 15:21
  • @FredLarson Sure, or at least an exercise in learning about recursion. Otherwise the OP could simply use the .count method. Commented Feb 8, 2018 at 15:25

1 Answer 1

6

the problem in your code is that you stop the recursion when you find the first a. You'll want to call get_a and collect the as you've already found:

def get_a(string):
    '''
    return how many times a exist in the string using recursion
    '''
    if string == '':
        return 0
    if string[0] == 'a':
        return 1 + get_a(string[1:])
    return get_a(string[1:])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.