首页 > 解决方案 > 更新:在python中查找数字列表的最小公倍数

问题描述

嗨,我已经用我的代码更新了这个:

输入->

a=[16,21, 56, 40]
def find_primes(a):
    num_factors=[] 
    for num in a:
       # print('1',num)
        list_of_factors=[]
        i=2
        while num>1:
            #print('2',num)
            if num%i==0:
                list_of_factors.append(i)
               # print('3',list_of_factors)
                num=num/i
               # print('4',num)
                i=i-1
                
            i+=1 
        num_factors.append(list_of_factors)  
    d = {}
    a_list = []
    for i in num_factors:
        for j in i:
            d[j] = d.get(j, 0) + 1
            dictionary_copy = d.copy()
    a_list.append(dictionary_copy)  
    print(a_list)
    return num_factors
    
find_primes(a)

这是我得到的输出:

[{2: 10, 3: 1, 7: 2, 5: 1}]
[[2, 2, 2, 2], [3, 7], [2, 2, 2, 7], [2, 2, 2, 5]]

这是我的问题:

理解,因为它是一个字典,所以键的值是累积的。

我想计算每个列表中唯一整数的数量。例如。[{2:4},{3:1,7:1},{2:3,7:1},{2:3,5:1}] 而不是上面代码输出中给出的内容。

之后,我想获得每个整数的最大出现次数来计算 LCM。2^4 * 3 * 7 * 5

请就我们如何改进代码提出建议。感谢帮助。

标签: pythonalgorithmlcm

解决方案


这可能是方法之一。

numbers=list(map(int,input().split()))
numbers.sort()
maximum=numbers[0]  #gcd of the input numbers cannot be greater than minimum number in the list.Therefore we are retrieving the mininum number of the list.
    gcd=1               #Initial value of gcd.
    for i in range(1,(maximum+1)):
        flag=0
        for j in range(len(numbers)):
            num=numbers[j]
            if num % i ==0:      #check if the every number in the input is divisible by the value of i
                 flag=1          #if divisible set flag=1 and then check the other numbers of the input.
            else:
                 flag=0          #if any of the number of the input is not divisible then flag =0 and go to next iteration of i.
                 break
        if flag==1:
            gcd=i         #if flag=1 that means every number of the input is divisible by the value of j.Update the value of gcd.
    
    print(gcd)

这可以通过以下方式完成:

for i in num_factors:
    d={}
    for j in i:
       
            try:
             d[j]=d[j]+1
            except KeyError:
             d[j]=1

    dictionary_copy = d.copy()
    a_list.append(dictionary_copy)  
print(a_list)
return num_factors

推荐阅读