5 Best Ways to Check if a String is Colindrome in Python

Rate this post

πŸ’‘ Problem Formulation: A colindrome is a string that can be split into two parts where the second part is a mirror image of the first one. For example, ‘aabbaa’ is a colindrome because the second half ‘baa’ is a mirror of the first half ‘aab’. This article explains how to check whether a given string is a colindrome using Python programming.

Method 1: Two-Pointer Technique

This method involves iterating over the string with two pointers, one starting from the beginning and another from the end of the first half of the string. It compares characters at each position, moving inwards, to check for mirroring.

Here’s an example:

def is_colindrome(s):
    n = len(s)
    for i in range(n//2):
        if s[i] != s[n//2 - i - 1]:
            return False
    return True

print(is_colindrome('aabbaa'))
print(is_colindrome('abcddcba'))

Output:

True
False

The code defines a function is_colindrome(s) that takes a single string argument s. It loops over the first half of the string and checks character by character if it mirrors the corresponding character from the end of the first half. If all the characters mirror correctly, the function returns True, indicating that the string is a colindrome, otherwise False.

Method 2: Slicing & Comparing Halves

This method involves slicing the string into two halves and checking if the first half is equal to the reverse of the second half. It’s a more Pythonic way of implementing the two-pointer technique using slicing.

Here’s an example:

def is_colindrome(s):
    n = len(s)
    return s[:n//2] == s[:n//2-1:-1]

print(is_colindrome('aabbaa'))
print(is_colindrome('aabcba'))

Output:

True
False

The function is_colindrome(s) slices the string into two halves and compares the first half to the reverse of the second half. This relies on Python’s powerful slicing capabilities and conciseness, which makes the code very readable and clear.

Method 3: Regular Expression Matching

Regular expressions can be used to craft a pattern that checks for colindromic structure. This involves constructing a pattern that matches the first half of the string followed by its reversed version.

Here’s an example:

import re

def is_colindrome(s):
    pattern = r'^(.*).?\1$'
    return bool(re.match(pattern, s))

print(is_colindrome('aabbaa'))
print(is_colindrome('abacdc'))

Output:

True
False

The function is_colindrome(s) uses the re module to compile a regular expression that matches any number of characters (captured as a group) followed by an optional center character (to handle odd lengths), then the same character group in reverse. It returns True if the pattern matches and False otherwise.

Method 4: Function Recursion

Using recursion, this method checks colindrome by recursively comparing the first and last character of the string, then slicing the string to examine the remaining part until it’s fully checked or fails to match.

Here’s an example:

def is_colindrome(s):
    if len(s) <= 1:
        return True
    if s[0] == s[-1]:
        return is_colindrome(s[1:-1])
    return False

print(is_colindrome('aabbaa'))
print(is_colindrome('abcd'))

Output:

True
False

The recursive function is_colindrome(s) checks if the first and last characters are equal, then calls itself but only on the string that is one character less on either end. This process continues recursively until the string can no longer be sliced or a mismatch is found.

Bonus One-Liner Method 5: Lambda Expression

For those who prefer concise code, a lambda function can be used that utilizes slicing to return the result in one line.

Here’s an example:

is_colindrome = lambda s: s[:len(s)//2] == s[-1:-(len(s)//2)-1:-1]

print(is_colindrome('aabbaa'))
print(is_colindrome('abcde'))

Output:

True
False

This one-liner lambda function takes in a string s and compares the first half to the reversed second half using slicing. It returns True if the string is colindrome, or False otherwise.

Summary/Discussion

  • Method 1: Two-Pointer Technique. Easy to understand. Requires iteration over half the length of the string. Can be slightly cumbersome to write.
  • Method 2: Slicing & Comparing Halves. Very Pythonic and concise. Relies on Python’s powerful features. Might be slightly less efficient for large strings due to slicing.
  • Method 3: Regular Expression Matching. Powerful for pattern matching. May be a bit overkill for this specific task and less readable for those not familiar with regex.
  • Method 4: Function Recursion. Elegant and simple. Has the overhead of recursive calls which can lead to stack overflow for very large strings.
  • Method 5: Lambda Expression. Extremely concise. Not as readable for beginners and hides complexity.