Skip to content

Instantly share code, notes, and snippets.

@luw2007
Last active December 17, 2015 09:58
Show Gist options
  • Select an option

  • Save luw2007/5590896 to your computer and use it in GitHub Desktop.

Select an option

Save luw2007/5590896 to your computer and use it in GitHub Desktop.
http://www.oschina.net/code/snippet_1026590_20768 给定数字X和Y,返回其中包括多少个数字,数字本身是回文数,同时也是另一个回文数的平方。 可能边界还存在问题,但是没有过多的用例验证.
#!/usr/bin/python
#-*- coding:utf-8 -*-
"""
给定数字X和Y,返回其中包括多少个数字,数字本身是回文数,同时也是另一个回文数的平方。
Given two numbers X and Y, return how many numbers in that range
(inclusive) are palindromes, and also the square of a palindrome.
"""
def get_numbers(deep):
if deep == 1:
return xrange(10)
else:
return (j.__add__(i.__mul__(10)) for i in get_numbers(deep - 1) for j in xrange(10))
#kernprof.py -l -v -b
#line_profiler
#@profile
def main(m1=1, m2=1000000000):
deep, is_odd = (len(str(m2))+1)/2, len(str(m2)) % 2
l = set()
for n in get_numbers(deep):
m = n.__str__()
for s in (int(m + m[::-1][1:]), int(m + m[::-1])):
if m1 <= s < m2:
x = str(s**2)
if x == x[::-1]:
l.add((s, s**2))
elif s >= m2 and is_odd:
return l
return l
if __name__ == "__main__":
def x(m1=1, m2=10000000000):
return len(main(m1, m2))
assert x(1, 1000000**0.5) == 10
#[(1, 1), (2, 4), (3, 9), (11, 121), (22, 484), (101, 10201), (111, 12321), (121, 14641), (202, 40804), (212, 44944)]
assert x(1, 1000000000000**0.5) == 26
#[(1, 1), (2, 4), (3, 9), (11, 121), (22, 484), (101, 10201), (111, 12321), (121, 14641), (202, 40804), (212, 44944), (1001, 1002001), (1111, 1234321), (2002, 4008004), (10001, 100020001), (10101, 102030201), (10201, 104060401), (11011, 121242121), (11111, 123454321), (11211, 125686521), (20002, 400080004), (20102, 404090404), (100001, 10000200001L), (101101, 10221412201L), (110011, 12102420121L),(111111, 12345654321L), (200002, 40000800004L)]
print x()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment