Largest number divisible by its digits: Difference between revisions

→‎{{header|Python}}: Added a Python draft for base 10
m (→‎Base 16: typo new-lines in output)
(→‎{{header|Python}}: Added a Python draft for base 10)
Line 541:
FEDCB59726A1348 / 4 = 3FB72D65C9A84D2 | 1147797065081426760 / 4 = 286949266270356690
FEDCB59726A1348 / 8 = 1FDB96B2E4D4269 | 1147797065081426760 / 8 = 143474633135178345</pre>
 
=={{header|Python}}==
===base 10===
Using the insights presented in the preamble to the '''Perl 6''' (base 10) example:
 
<lang python>from itertools import (chain, permutations)
from functools import (reduce)
from fractions import (gcd)
from math import (floor)
 
 
# MAIN :: IO ()
def main():
# (Division by zero is not an option, so we also 0 and 5)
# digits :: [Int]
digits = [1, 2, 3, 4, 6, 7, 8, 9]
 
# Least common multiple of the digits above
lcmDigits = foldl1(lcm)(digits)
 
# Any set of 7 distinct digits obtained by deleting
# [1, 4 or 7] from the list of 8 above
sevenDigits = _map(lambda x: delete(x)(digits))(
[1, 4, 7]
)
 
print (
maximumBy(lambda n: n if 0 == n % lcmDigits else 0)(
_map(unDigits)(
concat(_map(permutations)(sevenDigits))
)
)
)
 
 
# unDigits :: [Int] -> Int
def unDigits(xs):
return reduce(lambda a, x: a * 10 + x, xs, 0)
 
 
# GENERIC --------------------------------------------------
 
 
# concat :: [[a]] -> [a]
# concat :: [String] -> String
def concat(xxs):
xs = list(chain.from_iterable(xxs))
return [] if not xs else (
''.join(xs) if type(xs[0]) is str else xs
)
 
 
# delete :: Eq a => a -> [a] -> [a]
def delete(x):
def pruned(xs):
ys = xs.copy()
ys.remove(x)
return ys
return lambda xs: pruned(xs)
 
 
# foldl1 :: (a -> a -> a) -> [a] -> a
def foldl1(f):
return lambda xs: reduce(
uncurry(f), xs[1:], xs[0]
) if (len(xs) > 0) else None
 
 
# lcm :: Int -> Int -> Int
def lcm(x):
return lambda y: (
0 if (0 == x or 0 == y) else abs(
y * floor(x / gcd(x, y))
)
)
 
 
# map :: (a -> b) -> [a] -> [b]
def _map(f):
return lambda xs: list(map(f, xs))
 
 
# maximumBy :: (a -> a -> a) -> [a] -> a
def maximumBy(f):
def go(x, y):
return y if f(y) > f(x) else x
return lambda xs: reduce(go, xs[1:], xs[0])
 
 
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
return lambda x, y: f(x)(y)
 
 
# MAIN ---
main()</lang>
{{Out}}
<pre>9867312</pre>
 
=={{header|REXX}}==
9,655

edits