为了账号安全,请及时绑定邮箱和手机立即绑定

更新:在 python 中查找数字列表的最小公倍数

更新:在 python 中查找数字列表的最小公倍数

智慧大石 2023-09-12 16:59:47
您好,我已经用我的代码更新了此内容:输入->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请建议我们如何改进代码。感谢您的帮助。
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

这可能是其中一种方法。


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


查看完整回答
反对 回复 2023-09-12
  • 1 回答
  • 0 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信