import math import string def IsPallindrome(value): s = str(value) return s == s[::-1] def get_halfs(value): s = str(value) l = len(s) if l % 2 == 0: #even length return s[:l/2], s[l/2:] else: #odd length return s[:(l/2)], s[l/2], s[1+l/2:] #finds the first pallindrome, bigger than the input value def first_pallindrome(value): p = build_pallindrome(value) while int(p) < value: p = next_pallindrome(p) return p def build_pallindrome(value): s = str(value) if len(s)%2 == 0: half = s[:len(s)/2] return half + half[::-1] else: half, mid = s[:len(s)/2], s[len(s)/2] return half + mid + half[::-1] # assumes input is pallindrome def next_pallindrome(value): s = str(value) if len(s)%2 == 0: half = s[:len(s)/2] i = int(half) + 1 half = str(i) return half + half[::-1] else: half, mid = s[:len(s)/2], s[len(s)/2] i = int(mid) if i < 9: return half + str(i + 1) + half[::-1] else: half = str(int(half) + 1) return half + '0' + half[::-1] A, B = 1000, 9999 print str(str(3)) print first_pallindrome(112) print next_pallindrome(12921) p = first_pallindrome(A) print p while int(p) < B: p = next_pallindrome(p) print p
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