打印出第一个找到答案并退出循环的简便方法

时间:2016-12-13 23:08:06

标签: python

我正在做项目euler问题5,我只需要我的循环找到的第一个数字(因为它是最小的)并且我找不到找到第一个结果时摆脱循环的方法。尝试使用休息但它不起作用。这是我的代码:

"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"""


dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime;
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime

for x in range(20, 999999999, 20):  # step has to be 20 so the number can be divisible by 20
    if all(x % n == 0 for n in dividers):
        print(x)

结果:

/usr/bin/python3.5 "/home/michal/Desktop/Project Euler/Problem5.py"
232792560
465585120
698377680
931170240

Process finished with exit code 0

尝试休息,但它只打印出所有可被20整除的数字。

dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime;
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime

for x in range(20, 999999999, 20):  # step has to be 20 so the number can be divisible by 20
    if all(x % n == 0 for n in dividers):
        break
    print(x)

2 个答案:

答案 0 :(得分:2)

正如Luke所提到的那样,只需将我的print(x)移到for循环之外。 这是工作代码:

dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime;
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime

for x in range(20, 999999999, 20):  # step has to be 20 so the number can be divisible by 20
    if all(x % n == 0 for n in dividers):
        break
print(x)

答案 1 :(得分:0)

我建议把它变成一个函数:

def project_Euler_Problem5(dividers):
     for x in range(dividers[:-1], 999999999, dividers[:-1]):
        if all(x % n == 0 for n in dividers):
            return x

它还有一个额外的好处,就是当你经历过所有其他欧拉解决方案时(并保留旧版的欧莱克解决方案)。

有趣的事实:您也可以从2520而不是20开始,因为在答案的第一部分到达之前您将找不到答案。

编辑:当制作大范围(例如从20到999999999)时,我建议使用xrange(),因为它会使代码运行得更快(特别是如果你这样做的话)。

编辑:该功能只是打包您的代码。如果由于某种原因你想将它抽象为任意数量的除数,我会改变它以反映它。