0

新手在这里。我一直在尝试找到数字 1 到 10 的最小公倍数。到目前为止我的代码

def smallest_multiple():
a = 0
while True:
    a += 1
    if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0:
        return a

print(smallest_multiple())

我的结果是 2520,这似乎是正确的。它是可被数字 1 到 10 无余数整除的最小数字。但是有没有办法通过迭代它们来缩短 5 行(没有那么多模数)?我试过这样的东西

def smallest_multiple():
a = 0
while True:
    a += 1
    for i in range(1, 11):
        if a % i == 0:
            return a

print(smallest_multiple())

但这只会返回 1,而不是 2520。有没有办法让

if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0:

更短?

4

3 回答 3

1

你可以使用所有

def smallest_multiple():
    factors = [i for i in range(1, 11)]
    a = 0
    while True:
        a += 1
        if all([a % factor == 0 for factor in factors]):
            return a


print(smallest_multiple())

输出

2520

更新

正如@PatrickHaugh 所建议的,您可以避免创建列表:

def smallest_multiple():
    factors = range(1, 11)
    a = 0
    while True:
        a += 1
        if all(a % factor == 0 for factor in factors):
            return a


print(smallest_multiple())

输出

2520
于 2018-09-12T15:24:37.470 回答
1

你可以把它改成

if all([a%i == 0 for i in range(1,11)]):

All 接受一个列表,如果列表中的所有内容为 True,则返回 True

这使用一个简单的列表推导来遍历数字 1 到 10,并检查它们是否都为 Truea%i == 0

于 2018-09-12T15:21:06.647 回答
0

说到单行^^

虽然不是无限循环

import sys
next(i for i in xrange(1, sys.maxsize) if len([j for j in range(1,10) if i % j == 0]) == 9)
#=> 2520

这不是最有效的解决方案。

于 2018-09-12T15:31:40.577 回答