Probably there's a more efficient mathematical solution.
In any case, the algorithm can be improved, and there's also a bug.
First of all,
I recommend to put 500 and 12 into variables,
as you use them multiple times.
You can define them near the top of the file where they will be easy to see and tweak if necessary.
For example, since the run with 500 and 12 takes awfully long,
I used smaller values like 50 and 4 for testing while refactoring.
min_count = 12
max_range = 500
You have two nested loops:
first to calculate the cubes,
and then again to find the numbers that add up to the smallest number you found.
Assuming you have enough memory,
you could use a single pass to calculate the cubes
and at the same time store the i, j, k
compoments, like this:
items = []
for i, j, k in itertools.combinations(range(1, max_range), 3):
cube = i ** 3 + j ** 3 + k ** 3
items.append((cube, (i, j, k)))
I renamed the original list from l
(which is a very hard-to-read variable name) to items
.
Instead of the nested loops,
I used @Luke's technique with itertools.combinations
which is more compact.
In this version items
is not a simple list of numbers,
but a list of tuples: the cube
+ the tuple of (i, j, k)
.
You can sort this list by the first element of the tuple (by the cube
),
by passing a comparison function to items.sort
like this:
items.sort(lambda a, b: cmp(a[0], b[0]))
Finally, to print the items,
it's more natural to use "".format
instead of the complicated and hard to read string concatenation, like this:
for i in range(len(items) - min_count):
if items[i][0] == items[i + min_count - 1][0]:
number = items[i]
for j in range(min_count):
cube = items[i + j][0]
x, y, z = items[i + j][1]
print('{}={}^3+{}^3+{}^3'.format(cube, x, y, z))
break
3*500^3
which is the sum of 3 cubes in 12 different ways. Not the smallest such number. At the very least you should break out of thefor
loop once you've findi
such thatl[i] == l[i+12]
. As @vnp mentions, you actually wanti+11
. \$\endgroup\$501**3 + 1 + 1
isn't the smallest such number, but can only be expressed in 11 ways as the sum of three cubes less than or equal to 500? Why the artificial 500 bound? \$\endgroup\$