0

For this test string "A man, a plan, a canal: Panama"

This code is hitting start > end, returning True, but then somehow the result is evaluated to False and I'm not sure why. Check returns True, but then the parent isPalindrome returns False

def isPalindrome(self, s: str) -> bool:
    cleanString = s.lower()
    cleanString = ''.join(filter(str.isalpha, cleanString))     
    if len(cleanString) == 1:
        return True
    start = 0
    end = len(cleanString)-1
    return check(cleanString, start, end)
        
def check(s: str, start: int, end: int) -> bool:
    print(f'{s[start]} {start} : {s[end]} {end}')
    if start > end:
        return True
    if s[start] != s[end]:
        return False
    check(s, start + 1, end - 1)

print(isPalindrome("A man, a plan, a canal: Panama"))
  • 1
    Where you have `check(s, start + 1, end - 1)`, do you see why that causes a problem? Hint: If not, imagine you were trying to call *any other* function there. *Then what*? Did you, perhaps, want to do something with the value that you get back? Hint 2: in `isPalindrome`, you correctly wrote `return check(cleanString, start, end)`. Why did you not instead just write `check(cleanString, start, end)`? Why would that be incorrect? – Karl Knechtel Nov 28 '21 at 17:02
  • @KarlKnechtel Oh my god, DUH. Thank you! – Craig Lessard Nov 28 '21 at 17:06
  • It's a very common problem. The key is to understand that recursion *is not special*; what is special is having a problem that has an elegant recursive decomposition. – Karl Knechtel Nov 28 '21 at 17:07

0 Answers0