1

I'm trying to figure out how to write a recursive function (with only one parameter) that returns the number of times the substring “ou” appears in the string. Where I'm confused at is that I'm not allowed to use any built-in string functions other than len, or the string operators [] and [:] for indexing and splicing. So I can't use the find built-in find function

I remember seeing something like this, but it uses two parameters and it also uses the find() method

def count_it(target, key):
  index = target.find(key)
  if index >= 0:
    return 1 + count_it(target[index+len(key):], key)
  else:
    return 0
1
  • 3
    What type can the argument be? Are you allowed to pass in a tuple? Commented Nov 1, 2011 at 20:22

2 Answers 2

2

Very inefficient, but should work:

def count_it(target):
    if len(target) < 2:
        return 0
    else:
        return (target[:2] == 'ou') + count_it(target[1:])

See it working online: ideone

It's basically the same idea as the code you posted, except that it moves only one character at a time through the string instead of using find to jump ahead to the next match.

Sign up to request clarification or add additional context in comments.

2 Comments

It works!! I'm only a beginner, but why would you say that it's inefficient?
@Will S: The main problem is that x[1:] requires copying the entire string (apart from the first character). This gives an O(n*n) complexity.
0

Try this, it works for the general case (any value of key, not only 'ou'):

def count_it(target, key):
    if len(target) < len(key):
        return 0
    found = True
    for i in xrange(len(key)):
        if target[i] != key[i]:
            found = False
            break
    if found:
        return 1 + count_it(target[len(key):], key)
    else:
        return count_it(target[1:], key)

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.