You could use any()
to test the table, like so:
while any(n != 1 for n in table):
# do stuff
I think this is clearer than sum(table) > len(table)
.
Also, as @JoeClacks recommended, use a constant.
Complete revised solution:
MAX_DIVISOR = 20
table = list(range(1, MAX_DIVISOR+1))
result = 1
pf = 2
while any(n != 1 for n in table):
assert pf <= MAX_DIVISOR
flag = False
for i,n in enumerate(table):
if n % pf == 0:
table[i] = n//pf
flag = True
if flag:
result *= pf
else:
pf += 1
print(result)
I added an assert
to make sure that pf
only has legal values; this isn't needed as long as there is no bug in the code, but it can be a good idea to make code sanity-check itself.
I used i
and n
for the index and the number, rather than x
and y
.
I used Python's integer division operator //
rather than /
, so the code will work the same on Python 3.x as on Python 2.x. Also, the way I wrote the print
statement it will work equally well in Python 3.x and Python 2.x.
I changed the indentation to steps of 4 spaces in accordance with PEP 8.
http://www.python.org/dev/peps/pep-0008/
Note: I like this algorithm for solving this problem. It's elegant. Did you invent this, get it from a book, or what?
EDIT: Actually, Project Euler problem 5 has been discussed before here on StackOverflow. Here is an answer that I just compared to the above answer. This one is almost exactly ten times faster than the one above. It's a bit trickier though!
https://stackoverflow.com/a/8026041/166949