更新:在 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


请建议我们如何改进代码。感谢您的帮助。


智慧大石
浏览 43回答 1
1回答

qq_花开花谢_0

这可能是其中一种方法。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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python