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')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question