这是我对欧拉计划的第五个问题的解决方案,它要求从1到20 (含)的数字的最小公共倍数。是否有任何方法来改进while循环条件而不是使用sum?
table = range(1, 21)
result = 1
pf = 2
while sum(table) > len(table):
flag = False
for x, y in enumerate(table):
if y % pf == 0:
table[x] = y/pf
flag = True
if flag:
result *= pf
else:
pf += 1
print result发布于 2014-01-30 09:29:51
您的目的是在table中的所有条目变为1时终止循环。
while sum(table) > len(table):是一种相当模糊的表达意图的方式。我建议你
while max(table) > 1:或者更明显的短路
while any(x > 1 for x in table):发布于 2014-01-30 04:42:00
用常量。当你想回去尝试不同的价值时,就更容易理解了。
复制我的答案从堆栈溢出,也改变了周围的事情,因为这是代码审查。
MAX_FACTOR = 20 #The largest divisor we want to be able to divide by
#should have a general outline of the algorithm here
table = range(1,MAX_FACTOR + 1)
result = 1 #final result is stored here
currentFactor = 2 #what we're currently trying to divide by
while currentFactor <= MAX_FACTOR:
isDivisor = False #is the currentFactor a divisor
for x,y in enumerate(table):
if y % currentFactor == 0:
table[x] = y/currentFactor
isDivisor = True
if isDivisor:
result *= currentFactor
else:
currentFactor += 1
print resulthttps://codereview.stackexchange.com/questions/40402
复制相似问题