[英]Python shortening simple if statement
is it possible to make if statement shorter in this fragment of program?是否可以在此程序片段中缩短 if 语句?
for number in range(100):
if (number % 4 == 0 and number % 3 == 0 and number % 2 == 0):
Just use: if number % 12 == 0:
只需使用: if number % 12 == 0:
This is because 12 is the least common multiple of 4, 3, and 2.这是因为 12 是 4、3 和 2 的最小公倍数。
On Edit:在编辑:
Here is some code to compute the least common multiple of a list (or other iterable) of integers:下面是一些计算整数列表(或其他可迭代)的最小公倍数的代码:
from math import gcd
def pair_lcm(a,b):
return a*b//gcd(a,b)
def lcm(nums):
"""computes the lcm of iterable nums"""
m = 1
for num in nums:
m = pair_lcm(m,num)
return m
For example,例如,
>>> lcm(range(1,11))
2520
if you don't want to do the math to combine them:如果您不想计算将它们组合起来:
for number in range(100):
if all(number % n == 0 for n in (2, 3, 4)):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.