PS3,Q1. I am trying to write a recursive function that will find the number of times one string (key) is located in another string (target). It's a simple problem, but I am wondering how to count the number of times the key has been found in the target without using a global variable. (i.e. Is is possible to keep a count of how many times a recursive function has run without using a global variable?)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
You can pass a hidden parameter to the function, namely count, which defaults to 0, then increment it, and keep calling the function with the new count. Check: http://codepad.org/JY3D31c1
Interesting. Didn't know you could pass a hidden parameter. Thanks for the help.
here is one way to count things recursively
Not the answer you are looking for? Search for more explanations.
@bwCA: Thanks for the tip. But how do I get the output of the function to print? I know I could define a second function that simply prints what is returned in the count_letters function, but is there another way to do it?
Nvmd. Codepad doesn't print a return command, but python shell does. I wonder if I'm doing something wrong on codepad.
yeah. that makes sense. i don't know why i didn't think of that. thanks.