Question

The following works well for cart_product([1,2,3], [a,b,c], [v]), doesn't it also return duplicate cartesian product, if so, how to get unique cartesian products?

import itertools
def cart_product(*somelists):
    for element in itertools.product(*somelists):
        print element

also this doesn't seem to work when I pass in a list containing lists [ [1,2,3],[a,b,c],[v] ]

Was it helpful?

Solution

  1. To get only the unique elements, you can use set notation like this (Note: This doesnt guarantee the order)

    return list({element for element in itertools.product(*somelists)})
    

    or as per Paul Draper's comment we can do it like this

    list(set(itertools.product(*somelists)))
    

    If you want to maintain the order as well

    import itertools
    def cart_product(somelists):
        result, tempSet = [], set()
        for element in itertools.product(*somelists):
            if element not in tempSet:
            tempSet.add(element)
            result.append(element)
        return result
    
  2. To make your program work with list of lists, just change the function declaration from

    def cart_product(*somelists):
    

    to

    def cart_product(somelists):
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top