Entry 3287
Palindrome Reduction
Submitted by Kaleb Hornsby
on March 9, 2010 at 4:31 a.m.
Language: Python. Code size: 1.1 KB.
#!/usr/bin/python def partition(obj): """Return a triple of the first half, middle (if it exists), and last half of an iterable object. """ ctr, odd = divmod(len(obj), 2) fwd = obj[:ctr] if odd: mid = obj[ctr] aft = obj[ctr+1:] else: mid = None aft = obj[ctr:] return (fwd,mid,aft) def palindromic(obj): """Return the palindromicity of an object.""" if type(obj) == type(list()) or type(obj) == type(tuple()): pass else: obj = list(str(obj)) front,mid,rear = partition(obj) return front == rear[::-1] def reductio_ad_palindromo(num): """If a number is not palindromic, sum it and its reverse. Repeat until a a palindrome is found. Return a list of all attempts. """ num = int(num) # Make sure its an int. iterations = [] def pal(n): iterations.append(n) if not palindromic(int(n)): pal(n + int(str(n)[::-1])) pal(num) return iterations if __name__ == "__main__": from sys import argv print " ".join([str(i) for i in reductio_ad_palindromo(argv[1])])
This snippet took 0.01 seconds to highlight.
Back to the Entry List or Home.