Iterative vs. Recursive coding

Thomas Jollans thomas at jollybox.de
Thu Aug 19 17:41:36 EDT 2010


On Thursday 19 August 2010, it occurred to Baba to exclaim:
> def countSubStringMatchRecursive(target,key):
>     counter=0
>     fsi=0     #fsi=find string index
>     if len(key)==len(target):       #base case
>       if key==target:
>            counter+=1
>     elif len(key)<len(target):
>         while fsi<len(target):
>             fsi=target.find(key,fsi)
>             if fsi!=-1:
>                counter+=1
>             else:
>                 break
>             fsi=fsi+1
>     else:
>         print 'key is longer than target...'
> 
>     print '%s is %d times in the target string' %(key,counter)
> 
> countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcat
> atgc")

This is not recursive. In fact, it's exactly the same approach as
the first one, plus a bit of an if statement.

Take another good look at the definition of "recursion" I'm sure you were
given.
To sum it up:

"iterate": use a loop. and again. and again. and again. and again. and aga....

"recurse": consider. recurse.

This is another good one: 

http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg

 - Thomas

PS: If you think you're thinking, then you're really only thinking that
you're thinking. Or are you?



More information about the Python-list mailing list