【问题标题】:Implementing for loop in an if statement在 if 语句中实现 for 循环
【发布时间】:2018-04-17 16:56:56
【问题描述】:

我正在尝试解决项目欧拉问题:

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()

【问题讨论】:

  • 您可以使用范围来枚举 2 到 20 之间的所有值:for divisor in range(2,20+1):
  • 要被 10 整除的数字需要以零结尾。因此,您可以从 10 点开始并在 10 秒内向上移动。这将使您的代码速度提高 10 倍!
  • for in range() 似乎没有给出正确答案。
  • @CodeCupboard 你没看懂这个问题。这个数字应该能被从一到二十的所有数字整除
  • 我明白这一点,但是检查一个不以零结尾的数字是没有意义的,因为它总是失败。代码在每个循环中都有增量开始。

标签: python algorithm range


【解决方案1】:

您可以使用生成器表达式和 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()

【讨论】:

  • 这行得通!我不知道投反对票的原因。
  • 根据 jpp 的解决方案,您可以使用 start = 20start += 20 而不是 1 更快地得出解决方案。
  • 我已经重新考虑过了。
【解决方案2】:

这是一种利用生成器的解决方案。我看到的最小数字是 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

【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

    • 您的解决方案没有回答我的问题,因为我正在寻找一种方法来简化 if 声明
    • 不使用 if 将如何检查?减少了 if 的数量。这不是你要求的吗?
    猜你喜欢
    • 2016-06-16
    • 2019-06-09
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    相关资源
    最近更新 更多