euler/python/e118.py

46 lines
1.1 KiB
Python

from itertools import combinations, permutations
from lib_prime import is_prime_rabin_miller as is_prime
def as_number(xs) -> int:
return int("".join(map(str, xs)))
def list_diff(xs, ys):
xs = list(xs)
for y in ys:
xs.remove(y)
return xs
def combs(xs, size):
return sorted([p
for cs in combinations(xs, size)
for p in permutations(cs)])
def count(min_set_size: int, min_num: int, remaining: list[int]) -> int:
if not remaining:
return 1
result = 0
# There are no pandigital primes with 9 digits, so we only check till 8.
for set_size in range(min_set_size, 9):
for subset in combs(remaining, set_size):
n = as_number(subset)
if n > min_num and is_prime(n):
new_remaining = list_diff(remaining, subset)
result += count(set_size, n, new_remaining)
return result
def euler_118():
return count(1, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
if __name__ == "__main__":
solution = euler_118()
print("e118.py: " + str(solution))
assert(solution == 44680)