A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

anonymous

  • 5 years ago

Problem 1 of Problem set 3: for the recursive function, I got my code working by writing a function within a function, it's quite long compare to the iterative method. My question is: is there a way to write the recursive function using only one function?

  • This Question is Closed
  1. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    Yes, there's definitely a way to do that. My original solution used an extra argument to count occurrences, but polpak had a cool solution that just used the key and target strings.

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

    Sure, but the recursive solution doesn't really buy you much in terms of readability over the iterative one (which IMO is the only reason you'd want to use recursion). Additionally, to make a truely recursive solution you have to take a third argument (possibly defaulted to 0) to tell the sub-calls where to start their search. e.x. def subStringMatchExact(target,key,position=0): index = target.find(key,position) if index != -1: return (index,) + subStringMatchExact(target,key,index + len(key)) else: return ()

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

    once again the formatting of the code has been munged by the silly javascript interface on this website

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

    I'm pretty sure that's just the 'counting matches' problem, for which your solution was on the order of: index = find(target,key) if index == -1: return 0 else: return 1 + countsubstringmatchrecursive(target[index+len(key)], key)

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

    I remembered because I hadn't thought of doing it that way, and I was stuck with an extra argument too.

  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

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...

23

  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.