这个问题在这里已经有了答案:
Calculate the LCM of a list of given numbers in Python
(20 个回答)
去年关闭。
在本练习中,我需要想出一种方法来找到前 20 个自然数 (1-20) 的最小公倍数 (LCM)。
到目前为止,这是我得到的:
if exercise == 34:
lcm = 20
while lcm % 2 != 0 or \
lcm % 3 != 0 or \
lcm % 4 != 0 or \
lcm % 5 != 0 or \
lcm % 6 != 0 or \
lcm % 7 != 0 or \
lcm % 8 != 0 or \
lcm % 9 != 0 or \
lcm % 10 != 0 or \
lcm % 11 != 0 or \
lcm % 12 != 0 or \
lcm % 13 != 0 or \
lcm % 14 != 0 or \
lcm % 15 != 0 or \
lcm % 16 != 0 or \
lcm % 17 != 0 or \
lcm % 18 != 0 or \
lcm % 19 != 0 or \
lcm % 20 != 0:
lcm += 1
print(lcm)
是否有更有效的编码方法,而无需为循环中要考虑的每个潜在数字编写条件?
最佳答案
这是一个较短的版本,替换长版本 or
与 any
if excercise == 34:
lcm = 20
while any(lcm % i != 0 for i in range(2, 21)):
lcm += 1
print(lcm)
关于python - 如何减少语句中的条件数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63387968/