Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 19 Online
OpenStudy (anonymous):

I'm just getting back into this course after being busy for a while, and I'm on pset3. For the first part, I can't even think of a way to do it iteratively, but I've got some code for a recursive function. http://pastie.org/1874924 Right now that's returning None. I'm not even sure how that could happen right now in my code. Any help?

OpenStudy (anonymous):

from string import * def countSubStringMatchRecursive(target,key): count = 0 if find(target,key) != -1: count=1+countSubStringMatchRecursive(target[find(target,key) + 1:],key) return count this is my recursive. Yours looks closer to an iterative version

OpenStudy (anonymous):

here is an iterative version: from string import * def countSubStringMatch(target,key): limit=len(target) index=-1 count=0 while index <(limit): count=count+1 index=find(target,key,index+1) if index==-1: print 'End' break print index,count countSubStringMatch('gsca777777tsg77gcatsg77gcatgg77','7')

OpenStudy (anonymous):

When you recurse you don't preserve the value of count

OpenStudy (anonymous):

Or ... when you 'return from a recursion' you don't do anything with count. Not sure which is the correct way to say that

OpenStudy (carlsmith):

Remember all Python functions must return something. They will return whatever you've told them to return if you use a return statement, but they will return None if that is not the case. Whenever a function is called the execution of the main code freezes and will not continue until the function has returned a value, no matter how long that takes. If it has nothing to return, it just returns the value None, rather than nothing at all.

OpenStudy (carlsmith):

bwCA is right, you're not really incrementing `count`, you just creating a bunch of instances of the same function, each with its own independent, local variable by that name. I'm not sure what jpkita meant when they said that your code was looking more like an iterative function, it looks pretty obvious to me that it is a recursive function, just a bit of a buggy one. I think they might have meant that you're incrementing count as though it's in an iterative loop. That's a serious problem with your function you'll have to think on a bit.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!