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.
I need help on making this code faster. Right now I'm using double nested for-loops; is there a way I can change that?
from timeit import default_timer as timer
start = timer()
products = set()
for a in range(12, 100):
for b in range(102, 1000): # to get 9-digit: 2-digit * 3-digit
product = a * b
digits = list(str(a) + str(b) + str(product))
digits = [int(x) for x in digits]
if sorted(digits, key = int) == range(1, 10):
products.add(product)
for a in range(1, 10):
for b in range(1023, 10000): # other option is 1-digit * 4-digit
product = a * b
digits = list(str(a) + str(b) + str(product))
digits = [int(x) for x in digits]
if sorted(digits, key = int) == range(1, 10):
products.add(product)
ans = sum(list(products))
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)