5 Best Ways to Check if a Number Is a Palindrome in Octal in Python

πŸ’‘ Problem Formulation: We want to ascertain if an integer, when expressed in octal (base-8) representation, reads the same forwards and backwards. This is a typical exercise in understanding both number systems and string manipulation in Python. For instance, the decimal number 585 is a palindrome in octal as well (1111 in octal).

Method 1: Convert and Compare

This method involves converting the number to its octal representation using Python’s oct() function and then checking if the resulting string is the same both ways. It’s a straightforward, easy-to-understand approach.

Here’s an example:

def is_octal_palindrome(num):
    octal_num = oct(num)[2:]
    return octal_num == octal_num[::-1]

# Test the function
print(is_octal_palindrome(585)) # Decimal 585 equals to octal 1111

Output: True

This snippet defines a function is_octal_palindrome that takes an integer num, converts it to its octal equivalent without the '0o' prefix using slicing [2:], and then checks if this string is a palindrome by comparing it to its reverse [::-1].

Method 2: Recursive Check

Recursion can be used to check for palindromes. This method internally reverses the octal string and compares it to the original octal representation.

Here’s an example:

def recursive_octal_palindrome(octal_num):
    if len(octal_num) < 2:
        return True
    if octal_num[0] != octal_num[-1]:
        return False
    return recursive_octal_palindrome(octal_num[1:-1])

# Convert number to octal and remove '0o' prefix
octal_representation = oct(585)[2:]
print(recursive_octal_palindrome(octal_representation))

Output: True

The function recursive_octal_palindrome tests if the first and last characters of the octal string are the same and then calls itself on the string excluding the first and last characters. Base cases are provided for strings of length 0 or 1.

Method 3: Using a Stack

In this technique, we push each digit of the octal number onto a stack, and then pop them off to check against the original sequence of digits, which allows us to verify palindrome property.

Here’s an example:

def is_palindrome_using_stack(num):
    octal_num = oct(num)[2:]
    return list(octal_num) == list(reversed(octal_num))

# Test the function
print(is_palindrome_using_stack(585))

Output: True

Here, we convert the number into octal and compare two lists: the original octal digits and a reversed version. The use of lists with the reversed() function implicitly creates a stack to check for the palindrome condition.

Method 4: Two-Pointer Technique

The two-pointer technique involves iterating over the octal number from both ends towards the center and comparing the digits until they meet. This method is efficient as it checks the number in one pass without using additional memory for string operations.

Here’s an example:

def is_palindrome_two_pointers(num):
    octal_num = oct(num)[2:]
    left, right = 0, len(octal_num) - 1
    while left < right:
        if octal_num[left] != octal_num[right]:
            return False
        left, right = left + 1, right - 1
    return True

# Test the function
print(is_palindrome_two_pointers(585))

Output: True

The function is_palindrome_two_pointers initializes two pointers; one at the beginning and one at the end of the octal string, then moves them towards the center until they meet, verifying the palindrome condition at each step.

Bonus One-Liner Method 5: Lambda Function

The one-liner method uses a lambda function to create a compact version of the octal palindrome checker. It relies on negative string slicing to reverse the octal representation and check for palindromicity.

Here’s an example:

is_octal_palindrome = lambda num: oct(num)[2:] == oct(num)[2:][::-1]

# Test the lambda function
print(is_octal_palindrome(585))

Output: True

This compact lambda function assigns is_octal_palindrome to an inline function that immediately checks the palindrome property of an octal number, leveraging Python’s ability to express simple functions succinctly.

Summary/Discussion

  • Method 1: Convert and Compare. Easy and straightforward, this method might not be the most efficient one for very large numbers as string reversal can be resource-intensive.
  • Method 2: Recursive Check. This is an elegant, but less efficient solution for large numbers or for situations where function call overhead is a concern due to the depth of the recursion.
  • Method 3: Using a Stack. Conceptually clear, it uses more memory than necessary and is not as efficient as the two-pointer technique.
  • Method 4: Two-Pointer Technique. This is the most efficient method in terms of both time and space complexity, as it checks for palindrome in a single pass without creating additional strings.
  • Bonus Method 5: Lambda Function. It’s concise and pythonic, best for coders who appreciate elegance and brevity, but might be less readable for those new to Python or functional programming.