Number palindromes in any base

TrustyTony 0 Tallied Votes 262 Views Share

As Goddess Narues' C code in C forum was over my head and her critique of simplistic solution maybe overflowing the integer range was valid in C, I worked out a recursive solution more suitable to my brain in my preferable language. Maybe one day I put in C, now I am too lazy for that. Funny thing is that my simplistic solution is completely sufficient in Python as it has unlimitted precission integers.

This code deals any numeric base and also explains about issue is 100 palindromic or not and how to accept or refuse it according to your preference. I seperated that decission from palindrome function itself.

def drop_zeroes(n, radix=10):
    while n % radix == 0:
        n //= radix
    return n

def is_palindrome(n, radix=10, power=None):
    """ return True if number is palindrome number in base radix
        not accepting leading zeroes (100 is not palindrome),
        If you want, drop first trailing zeroes with drop_zeroes or
        provide correct power argument to include leading zeroes

    """
    #print('is_palindrome(%i, %i, %s)' % (n, radix, power))
    assert n >= 0 
    if not power:
        if n == 0:
            return True
        high_digit =  n
        power = 1
        # while entered allways, as n is not 0
        while high_digit:
            prev = high_digit
            high_digit = high_digit // radix
            power *= radix
        # going one loop past restored
        power //= radix
        high_digit = prev
    else:
        high_digit = n // power

    #print(n, power, high_digit)
        
    return ((high_digit == n % radix) and
            # remove high and low digit and recurse 
            is_palindrome((n - high_digit * power)/radix, radix=radix, power=power//radix//radix))

for t in range(10000):
    if is_palindrome(t):
        print('%i is palindrome.' % t)
    if is_palindrome(t, 16):
        print('0x%x is palindrome' % t )


print('100 without zeroes %s palindrome.' % 'is' if is_palindrome(drop_zeroes(100)) else 'is not')
print('00100 with leading zeroes %s palindrome.' % 'is' if is_palindrome(100, power=10000) else 'is not')