# [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.

## 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 on other sites
"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)

1. 1
Rutin
34
2. 2
3. 3
4. 4
5. 5

• 11
• 10
• 13
• 97
• 11
• ### Forum Statistics

• Total Topics
632974
• Total Posts
3009650
• ### Who's Online (See full list)

There are no registered users currently online

×