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

I just need a hint for problem set 3 - Question #1. I'm trying to write a recursive program that counts the number of matches with a target within a string. BUT how do I count it? I need to set the count=0, but then each time it passes the point it'll reset to 0; instead of actually counting. The only way I've found is to set it at the function level, meaning: def countfind(string, target, 0) Any hints?

OpenStudy (anonymous):

Parameters list should be (string ,target). In the function ,you can consider using (string[1:],target) to count target in substring. like: func(string,target) count=0 if find a target in string count+=1 else return 0 count+=func(substring,target) return count

OpenStudy (anonymous):

Thanks for your answer. i've tried that, but the problem is when you run the func() for the second time, it'll start from the top of the func() and set the count=0 again. maybe i'm not understanding something? i have an odd solution that actually stores the count inside the string. so it's like func(string+count, target). And i just gotta be careful that it doesn't interfere.

OpenStudy (anonymous):

maybe the 'count' i used confuse you.it is OK to set count=0 again. but if you want to count the substring ,you should return 0 if no found to stop recursion or return 1+func(substring,target). to call the func again. consider 【 return 1+func(substring , target) 】 ps:forgive my my poor English... i am a Chinese student

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!