2) A palindrome is a number or word that reads the same forwards or backwards, s
ID: 3697729 • Letter: 2
Question
2) A palindrome is a number or word that reads the same forwards or backwards, such as 236545632 and madamImadam
In this problem you will write a recursive function isPalindrome that takes a vector of digits and determines whether it is a palindrome. If it is a palindrome it returns the value 1, if it is not, it returns 0. For example isPalindrome( [ 1,3,4,4,3,1]) will return 1 while isPalindrome([1,2,3,4,5]) will return 0.
A recursive approach to this problem is to examine the beginning and ending cells in the vector you are given. For example if v(1) and v(end) are not the same, then we know this isn’t a palindrome so we can set result to 0.
However, if they are the same, then we can set result = isPalindrome of the vector made from stripping the end points from our original vector.
Another possibility is that we have a vector of one cell (always a Palindrome!!) or a vector of 0 cells (always a Palindrome!!). These are the base cases or anchors of the recursive process.
[page1image19264] [page1image19424] [page1image19592]
When we arrive at a vector of length 0 or 1, we are finished, and we must set the result variable to 1 (it's a palindrome). You can check the lengh of a vector with the Matlab function length(v)
To summarize, there are two possible pathways through your isPalindrome function:
If length of vector <= 1 set result to 1 (that means true, it's a palindrome)
Else check first and last values in vector
v(1) and v(end)
if they do not match set result to 0 (that means false,
If they match, check more bins/values in vector by
assigning to result the value of a recursive call on the subvector from 2 to end-1
When you have a solution, try it out on a few vectors to see if it works properly and debug if necessary. Here are some test cases:
isPalindrome([1])
isPalindrome([1 2])
isPalindrome([2 2])
isPalindrome([1 2 3])
isPalindrome([1 2 1])
You may want to put these statements in a script (along with a few more) to speed testing
When finished, zip your folder up and turn it in to the uploader. Make sure your name is in each file.
Explanation / Answer
Please find my recursive solution;
def isPalindrome(s):
return len(s) < 2 or s[0] == s[-1] and isPalindrome(s[1:-1])
print isPalindrome([2,3,4, 2])
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.