我编写了一个代码来查找数字列表的LCM(最低公倍数)但我的代码中似乎有错误.代码如下:
def final_lcm(thelist):
previous_thelist = thelist
prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist))
factors = 1
for i in prime_thelist:
factors = factors*i
new_thelist = returns_new_thelist(previous_thelist)
for i in range(1, 10000000000):
s_empty = []
for j in new_thelist:
if i % j == 0:
s_empty.append(True)
if len(new_thelist) == len(s_empty):
initial_lcm = i
break
final_lcm = factor*initial_lcm
return final_lcm
def returns_new_thelist(ll):
if 3 in ll:
ll.remove(3)
for i in ll:
if checks_if_prime(i) == True:
ll.remove(i)
return ll
def checks_if_prime(n):
if n == 2:
return True
import math
for i in range(math.ceil(0.5*n), 1, -1):
if n % i == 0:
return False
elif i == 2:
return True
print(final_lcm([1,2,3,4,5,6,7,8,9]))
Run Code Online (Sandbox Code Playgroud)
请原谅我糟糕的变量选择,请求您查看逻辑是否正确以及代码是否正常运行.
我得到的语法错误是"因素"是无效的语法,虽然我不同意这一点.请告诉我我的代码出错了.
Ana*_*tal 18
这是我所知道的最佳方式:
from math import gcd
a = [100, 200, 150] #will work for an int array of any length
lcm = a[0]
for i in a[1:]:
lcm = lcm*i/gcd(lcm, i)
print lcm
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.欢迎所有查询,贡献和评论:)
Tak*_*ual 18
适用于任意长的分母列表。
from math import gcd # Python versions 3.5 and above
#from fractions import gcd # Python versions below 3.5
from functools import reduce # Python version 3.x
def lcm(denominators):
return reduce(lambda a,b: a*b // gcd(a,b), denominators)
Run Code Online (Sandbox Code Playgroud)
例子:
>>> lcm([100, 200, 300])
600
Run Code Online (Sandbox Code Playgroud)
Ham*_*mza 10
从 Python 3.9lcm()
开始,数学库中添加了函数。可以使用以下签名调用它:
math.lcm(*integers)
Run Code Online (Sandbox Code Playgroud)
返回指定整数参数的最小公倍数。如果所有参数都不为零,则返回值是所有参数的倍数的最小正整数。如果任何参数为零,则返回值是
0
。lcm()
不带参数返回1
。
lcm(0,0)
定制解决方案忽略的任何类型的异常(例如)。在 Numpy v1.17(在撰写本文时,非发布开发版本)中有一个lcm
函数可以用于两个数字,例如:
import numpy as np
np.lcm(12, 20)
Run Code Online (Sandbox Code Playgroud)
或者对于多个数字,例如:
np.lcm.reduce([40, 12, 20])
Run Code Online (Sandbox Code Playgroud)
还有一个gcd
功能。
你的解决方案可能太冗长了......试试吧!
from functools import reduce # need this line if you're using Python3.x
def lcm(a, b):
if a > b:
greater = a
else:
greater = b
while True:
if greater % a == 0 and greater % b == 0:
lcm = greater
break
greater += 1
return lcm
def get_lcm_for(your_list):
return reduce(lambda x, y: lcm(x, y), your_list)
ans = get_lcm_for([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(ans)
Run Code Online (Sandbox Code Playgroud)