Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Two LIsts in Unique Way in Python

Tags:

python

list

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].

like image 250
krushers Avatar asked Aug 08 '12 23:08

krushers


People also ask

How do you combine two lists in Python?

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.

How do you merge two lists without duplicates in Python?

Use set() and list() to combine two lists while removing duplicates in the new list and keeping duplicates in original list. Call set(list_1) and set(list_2) to generate sets of the elements in list_1 and list_2 respectively which contain no duplicates.

How do I combine multiple lists into one list?

Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.

How do I merge nested lists in Python?

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.


1 Answers

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]
like image 159
Raymond Hettinger Avatar answered Oct 25 '22 01:10

Raymond Hettinger