python - How to generate a list of palindrome numbers within a given range? -


let's range : 1x120

this have tried:

>>> def ispalindrome(s):     ''' check if number palindrome '''     s = str(s)     return s == s[::-1]  >>> def generate_palindrome(minx,maxx):     ''' return list of palindrome number in given range '''     tmplist = []     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] 

however, o(n).

how improve algorithm make faster ?

ps. python 2.7

your method be:

palindromes = [x x in xrange(min, max) if ispalindrome(x)] 

the way can , have non-linear algorithm generate palindromes yourself, instead of testing.

a palindrome can generated taking previous palindrome, , adding same number left , right side, starting point.

let's start @ 1:

possible palindromes obtained adding each digit 1:9 left , right:

111 212 313 ... 

and also, have generate several entries every digit equal in range...


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -