#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Recursive palindrome """ def is_palindrome_rec(s: str) -> bool: """ Returns True if s is a palindrome and False otherwise """ if len(s) <= 1: return True else: return s[0] == s[-1] and is_palindrome_rec(s[1:-1]) print(is_palindrome_rec("racecar")) # Quitting early? print(is_palindrome_rec("racecat")) print(is_palindrome_rec("able was I ere I saw elba")) # %% Recursive palindrome with better output def is_palindrome_rec_out(s: str, indent: str = " ") -> bool: """ Returns True if s is a palindrome and False otherwise, With nice stack illustration. """ print(indent, "called with: ", s) if len(s) <= 1: print(indent, "base case") return True else: ans = s[0] == s[-1] and is_palindrome_rec_out(s[1:-1], indent + " ") print(indent, "About to return: ", ans) return ans # Note: This algorithm handles odd and even strings just fine # (think about base case) print(is_palindrome_rec_out("racecar")) print(is_palindrome_rec_out("racecat")) print(is_palindrome_rec_out("tacocat")) print(is_palindrome_rec_out("anutforajaroftuna")) print(is_palindrome_rec_out("able was I ere I saw elba")) print(is_palindrome_rec_out("neveroddoreven")) # https://www.grammarly.com/blog/16-surprisingly-funny-palindromes/