The so-called palindrome string, that is, a string from left to right reading and right-to-left reading is exactly the same. For example: "Level", "aaabbaaa", "Madam", "radar".
How can I tell if a string is a palindrome? The solution is as follows:
1. Take the exhaustive method (Brute force algorithm), enumerate and check (enumerate & check) whether the first and last items of a string are equivalent
2. Gradually reduce the scope of the check, if the first and last item of the string is equal, then remove the first and last item of the string, check the new strings, and so on
The code is as follows:
def ispalindrome (s):
If Len (s) < 2: #如果字符串只有0个或1个字符, then the string conforms to the definition of palindrome
Return True
If S[0]!=S[-1]: #如果字符串不止一个字符, then check that the first and last item of the string character are equal
Return False
Return Ispalindrome (S[1:-1]) #字串符的第一项和最后一项等同, so remove the first and last entries of the string character and proceed with the check
Str=input ("Please enter a string:")
If Ispalindrome (str):
Print (str+ "is a palindrome string")
Else
Print (str+ "not a palindrome string")
The results of the operation are as follows:
Please enter a string: Madam
Madam is a palindrome string
If you use the iterative (iteration) method, you can also solve the problem, but it is much more complex. So, whether to use recursion or iterative method requires careful consideration.
Reference: MIT Open Class: Introduction to Computer Science and Programming (4th lesson)
Attached: The simplest solution
def ispalindrome (s):
return s = = S[::-1]
Recursive method to determine whether a string is a palindrome (recursion palindrome Python)