Reputation: 73
I am working on Project Euler problem 5 and am using the following:
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
Is there a Python function with which I can combine factorization and factors like this function does? For example, if factors=[2, 3, 5]
and factorization=[2, 2, 3]
, the combined list should be [2, 2, 3, 5]
.
Upvotes: 7
Views: 700
Reputation: 226346
The terminology is "union of multisets".
It is implemented in Python using collections.Counter:
>>> from collections import Counter
>>> combined = Counter([2, 3, 5]) | Counter([2, 2, 3])
>>> list(combined.elements())
[2, 2, 3, 5]
Upvotes: 23