Recursive method to determine whether a string is a palindrome (recursion palindrome Python)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.