I posted a coding challenge in the second issue of learnbyexample weekly. I discuss the problem and Python/Perl solutions in this blog post.


Problem statement🔗

Find numbers from 1 to 10000 (inclusive) which reads the same in reversed form in both binary and decimal formats. For example, 33 in decimal is 100001 in binary and both of these are palindromic.


Python solution🔗

Here's one possible solution for this problem:

for n in range(1, 10001):
    dec_s = f'{n}'
    bin_s = f'{n:b}'
    if dec_s == dec_s[::-1] and bin_s == bin_s[::-1]:
        print(n)

Extending the above solution to include more comparisons is easy with built-in features:

for n in range(1, 10001):
    dec_s = f'{n}'
    bin_s = f'{n:b}'
    oct_s = f'{n:o}'
    if all(s == s[::-1] for s in (dec_s, bin_s, oct_s)):
        print(n)

As an exercise, extend this program further to include hexadecimal number comparison as well. Can you find out what's the first number that is greater than ten to satisfy all the four numeric formats?


Perl one-liner🔗

Here's a solution for CLI enthusiasts:

$ perl -le 'for (1..10000) { $bn = sprintf("%b", $_);
                print if ($_ eq reverse) && ($bn eq reverse $bn) }'
1
3
5
7
9
33
99
313
585
717
7447
9009

info See my Perl One-Liners Guide ebook if you are interested in learning to use Perl from the command-line.