0% found this document useful (0 votes)
19 views

Recursion On Non - Numerics

This document discusses using recursion to check if a string is a palindrome by comparing the first and last characters and recursively checking the substring in the middle. It provides examples of palindromic strings and defines a function that converts the string to lowercase characters only, then recursively checks if the first and last characters are equal and the middle substring is also a palindrome. This approach divides the problem into easier subproblems in a divide and conquer strategy.

Uploaded by

Richard Ding
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Recursion On Non - Numerics

This document discusses using recursion to check if a string is a palindrome by comparing the first and last characters and recursively checking the substring in the middle. It provides examples of palindromic strings and defines a function that converts the string to lowercase characters only, then recursively checks if the first and last characters are equal and the middle substring is also a palindrome. This approach divides the problem into easier subproblems in a divide and conquer strategy.

Uploaded by

Richard Ding
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Recursion

on non-numerics
How could we check whether a string of characters is a palindrome, i.e., reads the same forwards and backwards
Able was I ere I saw Elba aAributed to Napolean Are we not drawn onward, we few, drawn onward to new era?

How to we solve this recursive?


First, convert the string to just characters, by stripping out punctuaHon, and converHng upper case to lower case Then
Base case: a string of length 0 or 1 is a palindrome Recursive case:
If rst character matches last character, then is a palindrome if middle secHon is a palindrome

Example
Able was I ere I saw Elba ablewasiereisawleba isPalindrome(ablewasiereisawleba) is same as
a == a and isPalindrome(blewasiereisawleb)

def isPalindrome(s):! ! def toChars(s):! s = s.lower()! ans = ''! for c in s:! if c in 'abcdefghijklmnopqrstuvwxyz':! ans = ans + c! return ans! ! def isPal(s):! if len(s) <= 1:! return True! else:! return s[0] == s[-1] and isPal(s[1:-1])! ! return isPal(toChars(s))!

Divide and conquer


This is an example of a divide and conquer algorithm
Solve a hard problem by breaking it into a set of sub-problems such that:
Sub-problems are easier to solve than the original SoluHons of the sub-problems can be combined to solve the original

You might also like