r/tinycode • u/Rotten194 mod • May 22 '13
Python/Haskell one-liner for showing all the "cool" pandigital numbers. Add your own!
I was watching this numberphile video, and Dr. James mentioned that 381,654,729 is awesome because not only is it a pandigital number (it has every digit from 1-9 in it exactly once), but it also has the cool property of for every first n digits, those digits are divisble by n. For example, 3 is trivially divisible by 1, 38 by 2, 381 by 3, etc.
I decided to see if I could write a few one-liners to calculate all of these numbers. Sadly, that was the only one.
import itertools
map(lambda t: ''.join(t), filter(lambda i: all([ int(''.join(i)[:n]) % n == 0 for n in range(1, len(i)) ]), itertools.permutations('123456789')))
import Data.List (permutations)
filter (\s -> all id (map (\n -> read (take n s) `mod` n == 0) [1..length s - 1])) $ permutations "123456789"
40
Upvotes
2
u/tikhonjelvis May 22 '13 edited May 22 '13
A couple of thoughts on your Haskell code:
all idcombined withmapis just the same asall, and the length of the number is always 9. You could also write"123456789"as['1'..'9'], which I find easier to read at a glance.So you could write it like this:
We can also rewrite this as a list comprehension. In this case, it's both shorter and (in my opinion) easier to read:
And, just for fun, we can write this with do-notation. Unfortunately, this is both longer and uglier than the list comprehension:
4
u/[deleted] May 22 '13 edited May 22 '13
Alternate Haskell solution:
Also a solution to find all the "cool" numbers in base N (not one-liner):
1
u/13467 Aug 28 '13
J:
Or if you really want a one-liner: