Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在if语句中实现for循环_Python_Algorithm_Range - Fatal编程技术网

Python 在if语句中实现for循环

Python 在if语句中实现for循环,python,algorithm,range,Python,Algorithm,Range,我试图解决欧拉项目的问题: 2520是可以被每个数字除的最小数字 从1到10,没有任何余数。最小的正数是多少 能被1到20之间的所有数整除的数 我已经提出了下面的python解决方案,但是有没有办法在if中循环数字,而不必编写所有代码 def smallest_m(): start=1 while True: if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and

我试图解决欧拉项目的问题:

2520是可以被每个数字除的最小数字 从1到10,没有任何余数。最小的正数是多少 能被1到20之间的所有数整除的数

我已经提出了下面的python解决方案,但是有没有办法在
if
中循环数字,而不必编写所有代码

def smallest_m():
    start=1
    while True:
        if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0:
            print(start)
            break
        else:
            start+=1

smallest_m()
试试这个

n = 2520
result = True

for i in range(1, 11):
    if (n % i != 0):
        result = False

print(result)

可以使用生成器表达式和all函数:

def smallest_m():
    start = 1
    while True:
        if all(start % i == 0 for i in range(2, 20+1)):
            print(start)
            break
        else:
            start+=1

smallest_m()

这里有一个利用发电机的解决方案。我看到的最小数字是232792560

def smallest_m(n):
    for k in range(20, n, 20):
        match = True
        for i in range(1, 21):
            if k % i != 0:
                match = False
                break
        else:
            if match:
                yield k

res = next(smallest_m(2432902008176640001))

# 232792560

您可以使用一个范围来枚举范围(2,20+1)中除数的2到20之间的所有值:
:对于要除以10的数字,它需要以零结尾。因此,您可以从10开始,在10秒内向上移动。这将使你的代码速度提高10倍!in range()的
似乎没有给出正确的答案。@CodeCupboard您还没有理解这个问题。这个数字应该可以被1到20之间的所有数字整除。我明白,但是检查一个不以零结尾的数字是没有意义的,因为它总是失败的。代码以每个循环一个开始递增。您的解决方案没有回答我的问题,因为我正在寻找一种简化
if
语句的方法在不使用if的情况下,您将如何检查?国际单项体育联合会的数量已经减少。这不是你要的吗?这很有效!我不知道否决票的原因。根据jpp的解决方案,您可以使用
start=20
start+=20
而不是1来更快地得出解决方案。我已经重新考虑了这一点。