Currently I'm experimenting a little bit with recursive functions in Python. I've read some things on the internet about them and I also built some simple functioning recursive functions myself. Although, I'm still not sure how to use the base case.
I know that a well-designed recursive function satisfies the following rules:
- There is a base case.
- The recursive steps work towards the base case.
- The solutions of the subproblems provide a solution for the original problem.
Now I want to come down to the question that I have: Is it allowed to make up a base case from multiple statements?
In other words is the base case of the following self written script, valid?
def checkstring(n, string):
if len(string) == 1:
if string == n:
return 1
else:
return 0
if string[-1:] == n:
return 1 + checkstring(n, string[0:len(string) - 1])
else:
return checkstring(n, string[0:len(string) - 1])
print(checkstring('l', 'hello'))
checkstring(n, string[0:len(string) - 1])once and store the value, that would make the code clearer.if-branches, it's all good as long as it terminates at some point. You can put it in fancy words if you want, but in reality the criteria is very simple: "Does the function do what I want?" If it prints out the correct number then it's a "valid" function.