patternpythonMinor
Project Euler 38: Pandigital Multiples
Viewed 0 times
pandigitalprojectmultipleseuler
Problem
I just solved Project Euler 38 and was wondering if you guys could provide some suggestions on how to speed it up. I've tried adding extra conditions but they increase the time. Any ideas on how to optimize the numbers I'm checking would be appreciated.
from timeit import default_timer as timer
def create_pandigital_multiple(original_number):
num = str(original_number)
digits = range(1, 10)
if len(num) >= 5:
return 0
else:
temp = 2
while len(num) greatest:
ans = create_pandigital_multiple(k)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)Solution
- Checking
if len(num) >= 5is redundant because you only call the function withk
- Instead of sorted([int(x) for x in num])
you could compute justsorted(num)and compare that to aDIGITS = [str(i) for i in range(1, 10)]constant that you can compute outside the function.
- Most of the multiples end up longer than 9 digits. Testing len(num) == 9` before sorting the digits should be faster.
- You could take advantage of the example 918273645 provided in the problem statement. The number you are looking for must be greater or equal to that. For one thing, the first two digits must be in range 91 to 98, which is a small fraction of all the two-digit numbers you try.
Context
StackExchange Code Review Q#49321, answer score: 5
Revisions (0)
No revisions yet.