You have to decide a base case first. The point where the recursion unwinds and returns.
In this case the the base case would be the point where there are no (further) instances of a particular character, say X
, in the string. (if string.find(X) == -1: return count
) and the function makes no further calls to itself and returns with the number of instances it found, while trusting its previous caller information.
Recursion means a function calling itself from within, therefore creating a stack(at least in Python) of calls and every call is an individual and has a specified purpose with no knowledge whatsoever of what happened before it was called, unless provided, to which it adds its own result and returns(not strictly speaking). And this information has to be supplied by its invoker, its parent, or can be done using global variables which is not advisable.
So in this case that information is how many instances of that particular character were found by the parent function in the first fraction of the string. The initial function call, made by us, also needs to be supplied that information, since we are the root of all function calls and have no idea(as we haven't treaded the string) of how many X
s are there we can safely tell the initial call that since I haven't gone through the string and haven't found any or zero/0
X
therefore here's the string entire string and could you please tread the rest of it and find
out how many X
are in there. This 0
as a convenience could be the default argument of the function, or you have to supply the 0
every time you make the call.
When will the function call another function?
Recursion is breaking down the task into the most granular level(strictly speaking, maybe) and leave the rest to the (grand)child(ren). The most granular break down of this task would be find
ing a single instance of X
and passing the rest of the string from the point, exclusive(point + 1
) at which it occurred to the next call, and adding 1
to the count
which its parent function supplied it with.
if not string.find(X) == -1:
string = string[string.find(X) + 1:]
return countLetterString(char, string, count = count + 1)`
Counting X
in file through iteration/loop.
It would involve open
ing the file(TextFILE
), then text = read(TextFile)
ing it, text
is a str
ing. Then looping over each character (for char in text:
) , remember granularity, and each time char
(equals) == X
, increment count
by +=1
. Before you run the loop specify that you never went through the string
and therefore your count
for the number X
(in text
) was = 0
. (Sounds familiar?)
return count
.