In terms of readability, one major thing is spacing. PEP-8 recommends 2 blank lines between top level functions (although that's probably unnecessary for something this short), a space on each side of most binary operators including assignment, and a space after commas in places like sequences and function calls.
For more specific things in your code, there are a couple things that could be more clear.
if checksolve(a,b,c) and tuple((a,2*c,2*b)) not in results:
results.append(tuple((a,2*b,2*c)))
The tuple()
is unneeded since using parentheses like in (a,2*b,2*c)
is already the form of a tuple literal. Also while keeping your algorithm, we can change the loop to be more efficient. Since we don't care about the order of b
and c
, it's redundant to check numbers for c
that are less than b
(they will have already been tested when b
was that value previously). This avoids equivalent checksolve
calls, and can also simplify the logic since we don't have to check for duplicate solutions.
for b in range(1, a):
for c in range(b, a): # Start from b
if checksolve(a, b, c):
results.append((a, 2*b, 2*c))
For your main code, I like that you're using a with
to open the file and a __name__ == '__main__'
guard, but I think it would make sense to open it once for writing instead of once for every solution for appending. You might also want to put the logic into a main()
function for if you import the module somewhere else.
if __name__ == '__main__':
bar = Bar('computing', max=len(range(0, 1000002, 2)), suffix='%(percent)d%%')
with open('caro.txt', 'w') as f: # Will overwrite a current file instead of appending to
for a in range(0, 1000002, 2):
solutions = checknumber(a)
for solution in solutions:
x, y, z = solution
f.write(f'{x}={y}+{z}\n') # I'd prefer f-string formatting if on python>=3.6
bar.next()
All together this ran about 360 times as fast for me when doing up to 100.
However, even though this was an improvement to your algorithm, using a search solution like this at all is unnecessary. It's pretty simple to see that as we increase one term by two, the other should decrease by two. Implementing this is also about 3 times as fast as before, and completely removes the need for a separate function.
if __name__ == '__main__':
bar = Bar('computing', max=len(range(0, 1000002, 2)), suffix='%(percent)d%%')
with open('caro.txt', 'w') as f:
for a in range(0, 1000002, 2):
for off in range(2, a//2 + 1, 2):
f.write(f'{a}={off}+{a - off}\n')
bar.next()
Algorithmically, this will be very fast. However it's still going to be an issue for writing the output to the file. The size of output for all the numbers up to 1,000,000 like in your example would be somewhere around 5TB I believe. So I'd recommend sticking to a smaller size.