Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.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 内置模块,用于计算最小公倍数_Python - Fatal编程技术网

Python 内置模块,用于计算最小公倍数

Python 内置模块,用于计算最小公倍数,python,Python,我目前正在使用一个函数,该函数接受两个数字,并使用循环查找这些数字中最不常见的倍数 def lcm(x, y): """This function takes two integers and returns the L.C.M.""" # Choose the greater number if x > y: greater = x else: greater = y

我目前正在使用一个函数,该函数接受两个数字,并使用循环查找这些数字中最不常见的倍数

def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   # Choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm
Python中是否有一个内置模块可以执行此操作而不是编写自定义函数?

请尝试以下操作:

def lcm(x, y):
    from fractions import gcd # or can import gcd from `math` in Python 3
    return x * y // gcd(x, y)
在Python3.8及更早版本中 stdlib中没有内置这样的东西

但是,
math
库中有一个函数。(对于Python3.4或2.7,它被隐藏在
分数中,而在GCD上编写LCM是非常简单的:

def lcm(a, b):
    return abs(a*b) // math.gcd(a, b)

或者,如果您使用的是NumPy,那么它在相当长的一段时间内都带有一个函数。

要稍微简化您的代码:

def lcm(x, y):
    for currentPossibleLCM in range(max(x,y), (x*y)+1)
         if((currentPossibleLCM % x == 0) and (currentPossibleLCM % y == 0)):
              return currentPossibleLCM
运行时:Python 3.9中的O(x*y)

+
这可以通过以下方式获得。它还可以使用任意长度的参数,允许您找到2个以上整数的最小公倍数。

为什么要将导入放入函数中?为什么不?发布一个自包含的解决方案比假设用户可以在包含作用域中乱丢与解决当前问题无关的名称(如“gcd”)要好。如果您想将导入移动到包含作用域,这很好。在函数中包含导入有一个缺点:只有在执行此类函数时,才会发现任何缺少的模块。将所有导入无条件地放在模块顶部可以确保在加载模块时所有依赖项都可用。(当然,这不是标准库模块的问题。)^^^此外,导入时间可能会很昂贵。通常建议在模块导入时支付费用,而不是函数调用。@TimPeters我知道模块级别的
\uuuuuu all\uuuuuu
旨在公布公共名称,而包含作用域中的一些额外名称实际上不会造成任何损害。至于“为什么不”,样式指南确实说导入总是放在文件的顶部,但我认为更重要的原因是代码要提前知道它们的依赖关系。这使得浏览大型代码库更容易,并且在测试期间,这意味着从模块名称空间模拟/修补依赖项更简单。