Create a list of all 3 digit palindrome numbers in python

I can code this roughly, but is there an intuitive way to use a list or itertools, etc.

And also, how to do it if it is given the number of kdigits instead of three?

+5
source share
2 answers
>>> L = [int("%d%d%d" % (x,y,x)) for x in range(1,10) for y in range(10)]
>>> L
[101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252,
 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414,
 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575,
 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737,
 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898,
 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]

UPDATE: To increase memory efficiency and speed, you can replace string formatting and int conversion with x+y*10+x*100. Thanks @larsmans.

UPDATE 2: And this is for knumbers!

[int(''.join(map(str, (([x]+list(ys)+[z]+list(ys)[::-1]+[x]) if k%2
                  else ([x]+list(ys)+list(ys)[::-1]+[x])))))
            for x in range(1,10)
            for ys in itertools.permutations(range(10), k/2-1)
            for z in (range(10) if k%2 else (None,))]

And it is optimized for NOT using strings!

[sum([n*(10**i) for i,n in enumerate(([x]+list(ys)+[z]+list(ys)[::-1]+[x]) if k%2
                                else ([x]+list(ys)+list(ys)[::-1]+[x]))])
            for x in range(1,10)
            for ys in itertools.permutations(range(10), k/2-1)
            for z in (range(10) if k%2 else (None,))]

, 0, - , k%2 == 1 (k ).

!

+11

k - - :

palindromes = [x for x in itertools.permutations(string.digits, k) if x == x[::-1]]

- 3- , . , , @jadkik94 - () :

palindromes = [x + x[::-1] for x in permutations(digits, k//2)]

k - k, , 0-9 .

+2
source

All Articles