python - 更新:在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
请就我们如何改进代码提出建议。感谢帮助。
解决方案
这可能是方法之一。
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
推荐阅读
- twitter-bootstrap - css3:制作标题导航菜单
- angular - Angular 6 对 .NET Web API 的跨域 POST 请求返回 401(未经授权)
- firebase - 在创建云函数以响应特定节点上的 onDisconnect 事件时需要帮助 - Firebase
- google-drive-api - Google Drive REST API Get file returns 404 with scope "drive.file" only
- amazon-s3 - Google Cloud Storage CORS issue with Rails ActiveStorage
- ruby-on-rails - Heroku and Circle CI 2.0 Authentication with Ruby on Rails
- amazon-s3 - Failing to read data from s3 to a spark dataframe in Sagemaker
- docker - Docker compose spring boot redis connection issue
- cassandra - Cassandra 读取超时的正确行为是什么?
- python - 我需要让表单错误显示在我的引导模式模板上