Source

codeeval_challenges / 045_ReverseAdd / reverse_add.py

Full commit
#! /usr/bin/env python

import sys
from optparse import OptionParser

def reverse_number(number):
    """ Returns reversed value of number.

        Example:
        >>> reverse_number(1234)
        4321
        >>> reverse_number(4554)
        4554
    """
    number_list = list(str(number))
    number_list = reversed(number_list)
    return int(''.join(number_list))

def is_palindrome(number):
    """ Checks if number is a palindrome or not. 
        Returns True when number is palindrome, False otherwise.

        Example:
        >>> is_palindrome(132)
        False
        >>> is_palindrome(1331)
        True
    """
    return number == reverse_number(number)

def reverse_add(number, count=0):
    """ Add number to its reversed number until their sum is 
        a palindrome. Count keeps track of the number of 
        recursive iterations.
        Returns tuple of iterations used and palindrome.

        Example:
        >>> reverse_add(195)
        (4, 9339)
    """
    number = number + reverse_number(number)
    count += 1

    if not is_palindrome(number): 
        count, number = reverse_add(number, count)

    return (count, number)

def main():
    parser = OptionParser('%s testcase.txt' % __file__)
    args = parser.parse_args()[1]

    if len(args) < 1:
        parser.error("No input file provided.")

    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        if test != '':
            try:
                test_number = int(test)
            except ValueError:
                print "Invalid character '%s' in %s" % (test, args[0])
            count, number = reverse_add(test_number)
            print "%d %d" % (count, number)

    test_cases.close()


if __name__ == "__main__":
    main()