Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

Zico13

  • 3 years ago

About the 2008 6.00 OCW, in problem set 3 (Q1), how do I count the number of instances of the key in the target string using recursion?

  • This Question is Open
  1. rsmith6559
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    Generally, a recursive function has three parts. The "base case", which is when to stop calling the function, in this case when the end of the string is reached. Code for what you want to do as you're recursing. Before the base case is reached, and more recursion needs to be done. Code for what you want to do as the recursion "unwinds". After the base case is reached and the recursions are returning. Thinking recursively is tough to get used to, but well worth the effort.

  2. Zico13
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    @rsmith6559: Well, I do know the logical steps of recursion; I'm unsure of how to count the no. of recursions that occur. Thanks anyway.

  3. rsmith6559
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    The base case returns 0, and the others increment it before returning it.

  4. Zico13
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    @rsmith6559: But again when the recursion stops and control falls back to the base step, the returned value is 0!! :( Could you please check my test file?

    1 Attachment
  5. rsmith6559
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    def countSubStringMatchRecursive(target,key): # base case if( len( target ) == 0 ): return 0 else: # unwind return countSubStringMatchRecursive(target[i:],key) + 1

  6. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy