Today, I've been trying to get used to Pythons functional programming tools by solving Project-Euler tasks. To make them more interesting, I've solved them in one line. But I realized, that it is difficult to read online as only about 70 characters get displayed without a scrollbar. So I made multi-line solutions out of them.
These snippets are also good examples what's possible to do with Python and to show that Python is fast.
Problem 24
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
from itertools import permutations, islice
print(next(islice(permutations("0123456789"), 999999, 999999 + 1)))
Problem 29
How many distinct terms are in the sequence generated by $a^b$ for $2 \leq a \leq 100$ and $2 \leq b \leq 100$?
d = lambda top: len(set([a ** b for a in range(2, top + 1) for b in range(2, top + 1)]))
Problem 34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included.
from math import factorial
l = lambda n: reduce(lambda x, y: int(x) + factorial(int(y)), [d for d in "0" + str(n)])
print(reduce(lambda x, y: x + y, filter(lambda x: x == l(x), range(3, 100000))))
Problem 36
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
palindrom = (
lambda x: str(x) == str(x)[::-1] and str(bin(x))[2:] == str(bin(x))[2:][::-1]
)
d = lambda top: reduce(lambda x, y: x + y, filter(palindrom, range(0, top + 1)))
Problem 48
The series, $1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317$. Find the last ten digits of the series, $1^1 + 2^2 + 3^3 + ... + 1000^{1000}$.
d = lambda top: str(reduce(lambda x, y: x + y, [i ** i for i in range(1, top + 1)]))[
-10:
]
Problem 52
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits in some order.
digits = lambda n, p: set(str(n * p))
d = lambda n: all(digits(n, 1) == digits(n, x) for x in range(2, 7))
print(filter(d, range(0, 1000000)))
Problem 53
How many values of $\binom{n}{r}$, for $1 \leq r \leq n \leq 100$, exceed one-million?
from math import factorial as f
print(
sum(
(f(i) / (f(j) * f(i - j))) > 1000000 for i in range(1, 101) for j in range(1, i)
)
)
Problem 56
Considering natural numbers of the form, $a^b$, finding the maximum digital sum.
print(
max(
[
sum([int(c) for c in str(a ** b)])
for a in range(1, 100)
for b in range(1, 100)
]
)
)
Problem 97
Find the last ten digits of the non-Mersenne prime: $28433 \cdot 2^{7830457} + 1$.
print(28433 * (2 ** 7830457) + 1) % (10 ** 10)