我正在研究Project Euler问题5并使用以下内容:
def findLCM(k):
start=time.time()
primes=[2,3,5,7,11,13,17,19,23]
factors=[]
for factor in range(2,k):
if factor in primes:
factors.append(factor)
else:
factorization=[]
while factor!=1:
for prime in primes:
lastFactor=prime
if factor%prime==0:
factor/=prime
factorization.append(lastFactor)
break
tmpFactors=[]
for tmpFactor in factorization:
if tmpFactor not in factors:
factors.append(tmpFactor)
else:
tmpFactors.append(tmpFactor)
factors.remove(tmpFactor)
for tmpFactor in tmpFactors:
factors.append(tmpFactor)
print factors
product=1
for factor in factors:
product*=factor
factors.sort()
end=time.time()
fnTime=end-start
return product, fnTime, factors
是否有Python函数可以将因子分解和像这个函数一样的因子结合起来?例如,如果factors=[2, 3, 5]
和factorization=[2, 2, 3]
,则组合列表应为[2, 2, 3, 5]
。
答案 0 :(得分:23)
术语是“multisets”的结合。
使用 collections.Counter :
在Python中实现>>> from collections import Counter
>>> combined = Counter([2, 3, 5]) | Counter([2, 2, 3])
>>> list(combined.elements())
[2, 2, 3, 5]