Skip to content

Instantly share code, notes, and snippets.

@hminaya
Forked from imiric/capicua2.py
Last active December 16, 2015 18:59
Show Gist options
  • Save hminaya/5481553 to your computer and use it in GitHub Desktop.
Save hminaya/5481553 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def is_palindrome(num):
return str(num) == str(num)[::-1]
def closest_higher(target, collection) :
"""Return the closest number to `target` in `collection`
that is higher than `target`"""
return max((target - i, i) for i in collection if (target - i) < 0)[1]
def main():
palindromes = []
ranges = [[int(i) for i in line.split()] for line in open('seed.txt')]
ranges_flat = [i for r in ranges for i in r]
lo, hi = min(ranges_flat), max(ranges_flat)
while hi >= lo:
if is_palindrome(lo):
palindromes.append(lo)
lo += 1
total = 0
for lo, hi in ranges:
x = palindromes.index(closest_higher(lo, palindromes))
if hi > palindromes[-1]:
y = len(palindromes)
else:
y = palindromes.index(closest_higher(hi, palindromes))
p = palindromes[x:y]
c = len(p)
total += c
print '%6d => %7d : %d' % (lo, hi, c)
print 'TOTAL: %d' % total
if __name__ =='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment