Project Euler Solution 32: Pandigital products

Problem 32: Pandigital products is another nice combinatoric problem with digits.

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

Hint: Some products can be obtained in more than one way so be sure to only include it once in your sum.

My approach here is to take all the permutations of the digits and then take all possible partitions into two factors and the product. Each of the three partitions must have at least one character. Then I create integers from the digits and check whether the two factors actually yield the designated product. Results are collected in a set for automatic deduplication.

def solution() -> int:
    results = set()
    for digits in itertools.permutations("123456789"):
        for sep_1 in range(2, 7):
            for sep_2 in range(sep_1 + 1, 8):
                factor_1 = int("".join(digits[:sep_1]))
                factor_2 = int("".join(digits[sep_1:sep_2]))
                product = int("".join(digits[sep_2:]))
                if factor_1 * factor_2 == product:
                    results.add(product)
    return sum(results)

This runs 3.9 s and is fast enough.