杰瑞科技汇

Python判断回文数的方法有哪些?

Of course! Let's break down how to check if a string is a palindrome in Python.

Python判断回文数的方法有哪些?-图1
(图片来源网络,侵删)

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).

Here are several ways to do it in Python, from the most common and "Pythonic" to more fundamental approaches for learning.


Method 1: The Pythonic Way (Slicing)

This is the most concise and widely used method in Python. It leverages string slicing with a step of -1 to reverse the string.

The Code

def is_palindrome(s: str) -> bool:
    """
    Checks if a string is a palindrome, ignoring case and non-alphanumeric characters.
    """
    # 1. Clean the string: keep only alphanumeric characters and convert to lowercase
    cleaned_s = ''.join(char for char in s if char.isalnum()).lower()
    # 2. Compare the cleaned string with its reverse
    return cleaned_s == cleaned_s[::-1]
# --- Examples ---
print(f"'racecar' is a palindrome: {is_palindrome('racecar')}")  # True
print(f"'hello' is a palindrome: {is_palindrome('hello')}")      # False
print(f"'A man, a plan, a canal: Panama' is a palindrome: {is_palindrome('A man, a plan, a canal: Panama')}") # True
print(f"'No 'x' in 'Nixon'' is a palindrome: {is_palindrome('No x in Nixon')}") # True
print(f"'12321' is a palindrome: {is_palindrome('12321')}")      # True
print(f"'' is a palindrome: {is_palindrome('')}")                # True (empty string)

How It Works

  1. Cleaning the String:

    Python判断回文数的方法有哪些?-图2
    (图片来源网络,侵删)
    • char for char in s if char.isalnum(): This is a generator expression that iterates through each character in the input string s and keeps only those that are alphanumeric (letters or numbers). This effectively removes spaces, punctuation, and symbols.
    • ''.join(...): This joins the filtered characters back together into a new string.
    • .lower(): This converts the entire new string to lowercase to ensure the check is case-insensitive (e.g., 'A' is treated the same as 'a').
  2. Checking the Palindrome:

    • cleaned_s[::-1]: This is the magic of Python slicing. It means "create a slice of the string cleaned_s from the beginning to the end, but with a step of -1," which is a concise way to reverse the string.
    • cleaned_s == cleaned_s[::-1]: This compares the original cleaned string with its reversed version. If they are identical, the function returns True; otherwise, it returns False.

Method 2: The Two-Pointer Approach

This method is more manual but is very efficient and is a common pattern in technical interviews. It avoids creating a reversed copy of the string, which can save memory on extremely large strings.

The Code

def is_palindrome_two_pointers(s: str) -> bool:
    """
    Checks if a string is a palindrome using the two-pointer technique.
    """
    # 1. Clean the string (same as before)
    cleaned_s = ''.join(char for char in s if char.isalnum()).lower()
    # 2. Initialize two pointers, one at the start and one at the end
    left, right = 0, len(cleaned_s) - 1
    # 3. Loop until the pointers meet in the middle
    while left < right:
        # If the characters at the pointers don't match, it's not a palindrome
        if cleaned_s[left] != cleaned_s[right]:
            return False
        # Move the pointers towards the center
        left += 1
        right -= 1
    # If the loop completes, all characters matched
    return True
# --- Examples ---
print(f"'madam' is a palindrome: {is_palindrome_two_pointers('madam')}")      # True
print(f"'python' is a palindrome: {is_palindrome_two_pointers('python')}")    # False
print(f"'Able was I ere I saw Elba' is a palindrome: {is_palindrome_two_pointers('Able was I ere I saw Elba')}") # True

How It Works

  1. Cleaning: The initial cleaning step is identical to Method 1.
  2. Pointers: We set up two "pointers," which are just integer variables representing indices in the string. left starts at the beginning (index 0), and right starts at the end (index len(cleaned_s) - 1).
  3. Loop: We loop as long as the left pointer is to the left of the right pointer (left < right).
  4. Comparison: Inside the loop, we compare the characters at the left and right positions.
    • If they are not equal, we know immediately it's not a palindrome, so we can return False.
    • If they are equal, we move the left pointer one step to the right (left += 1) and the right pointer one step to the left (right -= 1).
  5. Completion: If the loop finishes without ever finding a mismatch, it means the string is a palindrome, and we return True.

Method 3: The Simple Loop (Reversing and Joining)

This is a more fundamental approach that explicitly builds the reversed string character by character, which is a good exercise for beginners.

The Code

def is_palindrome_loop(s: str) -> bool:
    """
    Checks if a string is a palindrome by building a reversed string with a loop.
    """
    # 1. Clean the string (same as before)
    cleaned_s = ''.join(char for char in s if char.isalnum()).lower()
    # 2. Build the reversed string manually
    reversed_s = ""
    for char in cleaned_s:
        reversed_s = char + reversed_s # Prepend the character to the string
    # 3. Compare the original and the reversed
    return cleaned_s == reversed_s
# --- Examples ---
print(f"'level' is a palindrome: {is_palindrome_loop('level')}")      # True
print(f"'world' is a palindrome: {is_palindrome_loop('world')}")      # False

How It Works

  1. Cleaning: Again, the same cleaning step.
  2. Building Reversed String: We initialize an empty string reversed_s. We then loop through the cleaned_s and, in each iteration, we add the current character to the beginning of reversed_s. This effectively builds the string in reverse order.
  3. Comparison: Finally, we compare the original cleaned_s with our manually constructed reversed_s.

Summary: Which Method Should You Use?

Method Pros Cons Best For
Slicing Most Pythonic, concise, and readable. Very fast for most use cases. Creates a full copy of the string in memory. Almost all situations. This is the standard, idiomatic way to do it in Python.
Two-Pointers Most memory-efficient. Can be faster for extremely large strings as it doesn't create a copy. Slightly more code to write. Less "obvious" to beginners. Technical interviews, performance-critical applications with huge strings, or when you can't use extra memory.
Simple Loop Very easy to understand the logic of reversing a string. Inefficient because string concatenation () in a loop is slow in Python. Learning the fundamentals of programming and string manipulation.

For everyday Python programming, Method 1 (Slicing) is the clear winner. It's the tool that Python developers expect to see.

Python判断回文数的方法有哪些?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇