我对 Stack Overflow 完全陌生,并且在编码方面完全是新手。但是,我正在努力工作,并尝试通过自学来发挥创造力。
现在,我正在尝试编写一个以多个数字作为输入并返回 LCM 的 LCM 函数(我知道对于 2 个数字的 LCM 有一个更简单的代码)。然而,我似乎已经碰壁了。不知道我做错了什么,但我的代码不起作用。也就是说,它给了我一个不正确的结果。
代码如下:
def product(sequence):
base = 1
for i in range(0,len(sequence)):
base *= sequence[i]
i += 1
return base
def is_prime(x):
if x < 2:
return True
else:
for n in range(2,x):
if x%n == 0:
return False
return True
def lcm(my_list):
base = []
new_list = sorted(my_list)
for x in range(0,len(new_list)):
for i in new_list:
for j in range(min(new_list),max(new_list)+1):
if is_prime(j) == True:
if i//j == 1 and i%j == 0:
new_list[x] = 1
elif i//j > 1 and i%j == 0:
new_list[x] == i//j
else:
new_list[x] = i
x = x+1
base.append(j)
return product(base)
我将不胜感激有关我的代码的任何建设性反馈,特别是如果有人能强调这不起作用的原因。
在此先感谢 python 社区!