Source

codeeval_challenges / 047_PalindromicRange / palindromic_range.py

#! /usr/bin/env python

import sys
from optparse import OptionParser

def is_palindrome(number):
    """ Checks if number is a numeric palindrome. 

        Returns an integer. 1 if it is a palindrome, 0 otherwise.
    """
    if str(number) == str(number)[::-1]:
        return 1
    return 0

def find_subranges(interval):
    """ Takes an interval and finds all subranges containing
        an even number of palindromes. These subranges are 
        counted and their total is returned.

        Returns Total amount of interesting subranges as integer.
    """
    palindromes = []
    for number in xrange(interval[0], interval[1]+1):
        palindromes.append(is_palindrome(number))

    interesting_ranges = 0
    for start in range(len(palindromes)):
        for end in range(start, len(palindromes)):

            pals_in_sub = sum(palindromes[start:end+1])
            if pals_in_sub % 2 == 0:
                interesting_ranges += 1
                
    return interesting_ranges 

def main():

    parser = OptionParser('%s testcase.txt' % __file__)
    options, args = parser.parse_args()

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

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

    for test in test_cases:

        interval = [int(x.strip()) for x in test.split()]
        assert len(interval) == 2

        ## find subranges with even numbers of palindromes 
        even_subranges = find_subranges(interval)
        print even_subranges

    test_cases.close()


if __name__ == "__main__":
    main()