You do not break recursive functions. Trying to do this says that you think about them wrong. Currently, your recursive call ignores the output, which means that recursion is pointless; any returns of is_pal(middle(str))
do not affect the return value of your function.
A recursive algorithm solves the input problem by decomposing the problem into a smaller problem, solving the regression of solving the smaller problem, and then using the smaller solution to build the correct solution to the larger problem. You do not "break" the internal challenges, you return the solution to one level. You do not know (or need to know), you need to know whether you are in an internal call or at a higher level. In any case, your function should do the same: return True if the argument is a palindrome and False if it is not.
The algorithm you are trying to implement is basically this:
- If the string has a length of 1, this is a palindrome (return True)
- Otherwise, if the first character matches the last character, then the input is a palindrome, if the middle characters are a palindrome.
So, this means that after you set the first and last characters, the same thing, the answer to “my input is a palindrome” is exactly the same as the answer to “the average character is a palindrome”. You must return a response in order to fulfill your contract. Thus, the recursive call should be return is_pal(middle(str))
, not just is_pal(middle(str))
. If it was a top-level call, then this is the answer; if this is not a top-level call, then an external call will be needed to answer an external problem (in this case, simply returning it).
Btw, your algorithm also has some other problems.
- You never return
False
, so the answer can never be False
(in this case you accidentally return None
, falling away from the end of the function, if the first and last characters do not match, and None
will probably be False
in most cases, but it still not quite right). - If the length of the string is zero , not 1 (what happens if an empty string is sent to or if a palindrome of even length is transmitted once, pairs of equal first and last characters are deleted), then you are not returning the correct answer, and in fact you are trying get the first and last character of an empty string, which will throw an exception.
source share