Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This problem is easier/more efficient to solve using a loop, but if you really, really want to write a recursive solution, let's see how to do it. First example, how to count the number of lower case letters in a string (this is the correct implementation of your <code>string()</code> function):</p> <pre><code>import string def countString(strg): if not strg: # if it's the empty string return 0 # then it has 0 letters elif strg[0] in string.ascii_lowercase: # if the first char is a letter return 1 + countString(strg[1:]) # add 1 and continue with recursion else: # if the first char is not a letter raise Exception, 'Incorrect Letters' # then throw an exception countString('abcd') =&gt; 4 countString('ab$cd') =&gt; Exception: Incorrect Letters </code></pre> <p>The above will return the number of lower case letters in the input string, or throw an exception if a non-letter character was found. Notice that you can't just print a message if a non-letter character appears, it's necessary to stop the recursion, too - that's why I'm raising an exception.</p> <p>Second example, how to count the number of occurrences of a character in a string (this answers the question in the title), it's similar to the previous example, but it only counts the character passed as parameter:</p> <pre><code>def countChar(strg, ch): if not strg: # if it's the empty string return 0 # then ch's count is 0 elif strg[0] == ch: # if the first char is ch return 1 + countChar(strg[1:], ch) # add 1 and continue with recursion else: # if the first char is not ch return countChar(strg[1:], ch) # simply continue with recursion countChar('abcdeabca', 'a') =&gt; 3 countChar('abcdeabca', 'x') =&gt; 0 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload