adhamncheese
adhamncheese

Reputation: 111

Count 2 (or more) characters recursively in string; return in (x,y) format in Python

I have written a program that will count how many ' ' single spaces or h characters in a string you enter when you call the function:

def chars(s):
    if not s:
        return 0
    else:
        return (s[0] == 'h') + chars(s[1:])

When you call chars('hello how are you here')

You will get 3.

Now, let's say I want to count the e along with the h. The h will return a 3 and the e should return a 4. Output would be (3,4).

I tried def chars(s, j=0)and set a counter but then realized, hold on, this has no connection to anything at this point deeming it pointless. I guess, how would I define what that second variable is? Because I only want 1 string as an input.

I am completely lost on how to include that second variable.

Also, just throwing it out there, would I follow the same rules as for 2 characters for more characters? Or would there be a different way?

Upvotes: 1

Views: 81

Answers (1)

itdoesntwork
itdoesntwork

Reputation: 4802

This is what you want:

def count(s):
    if not s:
        return (0, 0)
    else:
        next_count = count(s[1:])
        return ((s[0] == 'h') + next_count[0],
                (s[0] == 'e') + next_count[1])

count("hello how are you here") # => (3, 4)

The base case returns the tuple (0, 0) and the recursive step looks at both of the values of the next count and adds one to each if necessary.

If you want more than 2 characters, just make the tuples bigger (probably using loops).

Upvotes: 1

Related Questions