# codeeval_challenges / 047_PalindromicRange / palindromic_range.py

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 #! /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()