Jump to content
  • Advertisement
Sign in to follow this  

[python]Recursion help

This topic is 3016 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I can't quite wrap my head around recursion, I get the gist of it but it just doesn't click when faced with anything other than the most simple of problems.

I've completed the iteration part of the problem easily, but I just don't understand recursion...

"Let’s start with a fairly simple problem. Suppose we want to count the number of times that a key string appears in a target string. We are going to create two different functions to accomplish this task: one iterative, and one recursive. For both functions, you can rely on Python’s find function."

If someone could try to explain recursion in some odd way that it just kinda clicks that would be nice, maybe a couple hints about the problem could also help me understand it...[Problem is from MIT open courseware, not homework]

Share this post

Link to post
Share on other sites

We're searching for "Hello".

Recursive problems can be expressed like this:
CurrentElement + (Everything else)

In above case, we could say:

'H' + 'iHelloHeyHelloYoHello!'
The recorsive relation is applied to remainder
'i' + 'HelloHeyHelloYoHello!'
'H' + 'elloHeyHelloYoHello!'
'e' + 'lloHeyHelloYoHello!'

And so on...

There are now several ways to structure the original problem like that. One way is to use some string search routine to find the first occurrence of 'Hello'.

First search would return 2 (first Hello appears at index 2). So we'd end up with:

'Hello' + 'HeyHelloYoHello!' (Hi was already discarded)
We repeat the search on the remainder, which results in
'Hello' + 'YoHello!'
And again
'Hello' + '!'
'!' + 0
Which results in
0 (0 means empty set, or no more elements, which is the terminating condition)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!