Chris Chris - 1 month ago 6
Python Question

I need to write a Python function to count how many times a character in string

This is what I have so far:

def count2(char,text):
if len(text)==0:
return 0
else:
if char==count2(char,text[:-1]):
return (1+count2(char,text[:-1]))
else:
return False


It will just go to false, but I am trying to count how many times "char" equals each character of "text."

Answer

Your base case looks correct. For your recursive case, lets take a look at the logic. There are two possible cases:

  1. If the first character of the current string is the one you are looking for. In this case, you should return 1 + the count of the character in the rest of the string.
  2. If the first character is not equal, then you should just return the count of the character in the rest of the string.

The function thus becomes

def count2(char,text):
    if len(text)== 0:
        return 0
    count = 0
    if text[0] == char:
        count = 1
    return count + count2(char, text[1:]) 
Comments