我已经编写了一个代码来找出数字列表的 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]))
请原谅我对变量的错误选择,我请你看看逻辑是否正确以及代码是否正常运行。
我得到的语法错误是“因素”是无效语法,尽管我不同意这一点。请告诉我我的代码哪里错了。
最佳答案
这是我所知道的最好的方法:
from math import gcd
a = [100, 200, 150] #will work for an int array of any length
lcm = 1
for i in a:
lcm = lcm*i//gcd(lcm, i)
print(lcm)
希望这对您有所帮助。欢迎所有查询、贡献和评论:)
关于python - 在 Python 中计算给定数字列表的 LCM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237954/