5 Best Ways to Check If All Elements of an Array Are Palindrome in Python

Rate this post

πŸ’‘ Problem Formulation: You’re given an array of strings, and your task is to determine whether every element in this collection is a palindrome or not. A palindrome is a word, number, phrase, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). The desired output is a simple boolean value: True if all elements are palindromes, otherwise False. For instance, given the input array [‘radar’, ‘level’, ‘rotor’], the output should be True.

Method 1: Using a Loop and Slicing

This method involves iterating over the array elements and checking whether each element is a palindrome by using Python slicing to reverse the string. If all elements are palindromic, the function returns True; otherwise, it returns False.

Here’s an example:

def check_palindromes(array):
    for element in array:
        if element != element[::-1]:
            return False
    return True

array = ['radar', 'level', 'rotor']
print(f"All elements are palindrome: {check_palindromes(array)}")

Output:

All elements are palindrome: True

This code defines a function check_palindromes() that iterates through each string in the given array. It uses the slicing feature element[::-1] to reverse the string and compares it with the original string. If they are equal, the string is a palindrome.

Method 2: Using the all() Function with a Generator Expression

The all() function, combined with a generator expression, offers a concise approach to checking for palindromes. A generator expression checks each element in an array to see if it’s equal to its reversed version, and all() returns True if all evaluations are true.

Here’s an example:

def all_palindromes(array):
    return all(element == element[::-1] for element in array)

array = ['radar', 'level', 'rotor']
print(f"All elements are palindrome: {all_palindromes(array)}")

Output:

All elements are palindrome: True

In this example, the one-liner function all_palindromes() uses a generator expression to create an iterator that produces the palindrome check for each element. The all() function then iterates through these results to ensure all are True.

Method 3: Using Recursion

Recursion can be applied to determine if a string is a palindrome by comparing the first and last characters, and then using a recursive call to compare the remaining substring.

Here’s an example:

def is_palindrome(s):
    if len(s) <= 1: 
        return True
    else:
        return s[0] == s[-1] and is_palindrome(s[1:-1])

def check_all_palindromes(array):
    return all(is_palindrome(element) for element in array)

array = ['radar', 'level', 'rotor']
print(f"All elements are palindrome: {check_all_palindromes(array)}")

Output:

All elements are palindrome: True

The function is_palindrome() is a recursive function that verifies if a given string is a palindrome. The function check_all_palindromes() uses the all() function along with the is_palindrome() to check each element in the array.

Method 4: Using functools.reduce()

With functools.reduce(), a cumulative operation is performed on the array elements. We apply a logical and operation on palindrome checks for each string in the array.

Here’s an example:

from functools import reduce

def all_palindromes(array):
    return reduce(lambda acc, x: acc and x == x[::-1], array, True)

array = ['radar', 'level', 'rotor']
print(f"All elements are palindrome: {all_palindromes(array)}")

Output:

All elements are palindrome: True

functools.reduce() is used with a lambda function that performs an and operation on its accumulator acc and the palindrome check. The third argument, True, initializes the accumulator, ensuring the default value represents logical True.

Bonus One-Liner Method 5: Using map() and all()

A more concise one-liner employs both map() and all() functions to determine if all array elements are palindromes. map() applies a palindrome check across all elements, and all() checks the result.

Here’s an example:

array = ['radar', 'level', 'rotor']
print(f"All elements are palindrome: {all(map(lambda x: x == x[::-1], array))}")

Output:

All elements are palindrome: True

The line of code uses map() to apply a lambda function that checks each element for being a palindrome. The resulting boolean values are then passed to the all() function to verify that every value is True.

Summary/Discussion

  • Method 1: Loop and Slicing. Straightforward and clear. No external dependencies. Can be less efficient with longer lists.
  • Method 2: Using all() and a Generator Expression. Very Pythonic and concise. High performance for large arrays. The succinctness may obscure code readability for novices.
  • Method 3: Recursion. Educational in understanding recursive problem-solving. Not as efficient as iterative solutions. Python has a limit on recursion depth.
  • Method 4: functools.reduce(). Functional programming approach. Can be more difficult to understand for those unfamiliar with reduce concepts.
  • Method 5: Map and All One-Liner. Extremely concise. May be less readable. Effective for performing operations in a functional style.