Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.
Click here to check if anything new just came in.
March 09 2010
Reduction ad Palindromo
My Programming Languages professor assigned the following as an assignment today:
I am not sure what she means by this antecedent, "if the statement turns out to be false," but Python's got the antecedent covered. Python will stop a recursion automatically after 1000 loops, that is unless it is told otherwise.
It is claimed that all numbers, when reversed and added to theirThe following is my solution:
reversal repeatedly, will eventually become palindromes. Write a
program that allows a user to enter a number and then displays the
series of efforts to find its palindrome. If the statement turns out
to be false, stop iteration of your program after some number of tries
to find the palindrome.
#!/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__": """Since this most likely will be ran from `bash`, return the array in the form of a space delimited `bash` array.""" from sys import argv print " ".join([str(i) for i in reductio_ad_palindromo(argv[1])])
I am not sure what she means by this antecedent, "if the statement turns out to be false," but Python's got the antecedent covered. Python will stop a recursion automatically after 1000 loops, that is unless it is told otherwise.
