Search code examples
pythonpython-itertools

Generate a lattice using python


How to generate something like

[(), (1,), (1,2), (1,2,3)..., (1,2,3,...n)]

and

[(), (4,), (4,5), (4,5,6)..., (4,5,6,...m)]

then take the product of them and merge into

[(), (1,), (1,4), (1,4,5), (1,4,5,6), (1,2), (1,2,4)....(1,2,3,...n,4,5,6,...m)]

?

For the first two lists I've tried the powerset recipe in https://docs.python.org/2/library/itertools.html#recipes , but there will be something I don't want, like (1,3), (2,3)

For the product I've tested with chain and product, but I just can't merge the combinations of tuples into one.

Any idea how to do this nice and clean? Thanks!


Solution

  • Please note that, single element tuples are denoted like this (1,).

    a = [(), (1,), (1, 2), (1, 2, 3)]
    b = [(), (4,), (4, 5), (4, 5, 6)]
    
    from itertools import product
    for item1, item2 in product(a, b):
        print item1 + item2
    

    Output

    ()
    (4,)
    (4, 5)
    (4, 5, 6)
    (1,)
    (1, 4)
    (1, 4, 5)
    (1, 4, 5, 6)
    (1, 2)
    (1, 2, 4)
    (1, 2, 4, 5)
    (1, 2, 4, 5, 6)
    (1, 2, 3)
    (1, 2, 3, 4)
    (1, 2, 3, 4, 5)
    (1, 2, 3, 4, 5, 6)
    

    If you want them in a list, you can use list comprehension like this

    from itertools import product
    print [sum(items, ()) for items in product(a, b)]
    

    Or even simpler,

    print [items[0] + items[1] for items in product(a, b)]