[python]Recursion help

Started by
0 comments, last by Antheus 13 years, 9 months ago
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]
Advertisement
"HiHelloHeyHelloYoHello!"

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' + '!'Finally'!' + 0Which results in0 (0 means empty set, or no more elements, which is the terminating condition)

This topic is closed to new replies.

Advertisement