假設的範圍是:≤X
≤如何生成給定範圍內的迴文數字列表?
這是我曾嘗試:
>>> def isPalindrome(s):
''' check if a number is a Palindrome '''
s = str(s)
return s == s[::-1]
>>> def generate_palindrome(minx,maxx):
''' return a list of Palindrome number in a given range '''
tmpList = []
for i in range(minx,maxx+1):
if isPalindrome(i):
tmpList.append(i)
return tmpList
>>> generate_palindrome(1,120)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111]
然而,這是O(n)
。
如何改進此算法以使其更快?
PS。這是Python 2.7版