Problem 1 of Problem set 3: for the recursive function, I got my code working by writing a function within a function, it's quite long compare to the iterative method. My question is: is there a way to write the recursive function using only one function?
Yes, there's definitely a way to do that. My original solution used an extra argument to count occurrences, but polpak had a cool solution that just used the key and target strings.
Sure, but the recursive solution doesn't really buy you much in terms of readability over the iterative one (which IMO is the only reason you'd want to use recursion). Additionally, to make a truely recursive solution you have to take a third argument (possibly defaulted to 0) to tell the sub-calls where to start their search. e.x. def subStringMatchExact(target,key,position=0): index = target.find(key,position) if index != -1: return (index,) + subStringMatchExact(target,key,index + len(key)) else: return ()
once again the formatting of the code has been munged by the silly javascript interface on this website
I'm pretty sure that's just the 'counting matches' problem, for which your solution was on the order of: index = find(target,key) if index == -1: return 0 else: return 1 + countsubstringmatchrecursive(target[index+len(key)], key)
I remembered because I hadn't thought of doing it that way, and I was stuck with an extra argument too.
Join our real-time social learning platform and learn together with your friends!