我目前使用的函数接受两个数字,并使用循环查找这些数字的最小公倍数,
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
Run Code Online (Sandbox Code Playgroud)
python是否有内置模块可以代替编写自定义函数呢?
aba*_*ert 13
stdlib中没有内置这样的东西。
但是,库中有一个Greatest Common Divisor函数math。(对于Python 3.4或2.7,则将其埋藏fractions。)在GCD之上编写LCM非常简单:
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的是NumPy,它lcm现在已经有一段时间了。
尝试以下方法:
def lcm(x, y):
from fractions import gcd # or can import gcd from `math` in Python 3
return x * y // gcd(x, y)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7217 次 |
| 最近记录: |