'Generate list of all palindromic numbers of 3 digits in python
I want to generate list of all palindromic numbers of 3 digits in python. I can code this in a crude way but is there some intuitive way using list comprehension or itertools etc?
And also, How to do it if it is given the number is k digits instead of just 3?
Solution 1:[1]
For the generalisation to k digits, the most obvious way is to do something like:
palindromes = [x for x in itertools.permutations(string.digits, k) if x == x[::-1]]
But it isn't very efficient - it generates every possible 3-digit number, and discards the ones that aren't palindromes. However, it is possible to generalise solutions like @jadkik94's - what you need to do is generate every combination of half the length (rounding down), and stick the mirror of it on the end:
palindromes = [x + x[::-1] for x in permutations(digits, k//2)]
Will work for all even k - for odd k, you add an extra loop to put all of 0-9 in between the mirrored halves.
Solution 2:[2]
The simplest way would be converting the numbers to strings and checking if they are palindromes. To find the palindromes of the "k" number of digits, the list comprehension could be;
palindromes = [num for num in range(pow(10,k-1),pow(10,k)) if str(num) == str(num)[::-1]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lvc |
| Solution 2 | Deepeshkumar |
