0

I have a list of points

lst = [1,2,3,4,5]

With itertools I get all possible combinations of lines ((1,2)=(2,1)): itertools.combinations(lst, 2)

[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

I want to get list of lists of tuples(with unique points), like this

   [
    [(1,2),(3,4)],
    [(1,2),(3,5)],
    [(1,2),(4,5)],
    [(1,3),(2,4)],
    [(1,3),(2,5)],
    ...
    [(2,3),(4,5)]
   ]

1 Answers1

1

Ok, this is interesting xD. All you need is provided by itertools, you just have to combine it the correct way. Have a look at this:

import itertools


lst = [1,2,3,4,5]

points = list(itertools.combinations(lst, 2))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

f = lambda p: filter(lambda sub: not any(x in sub for x in p), points)

res = []
for p in points:
    res.extend(list(itertools.product([p], f(p))))

# corresponding list-comprehension solution
# res = list(itertools.chain.from_iterable(itertools.product([p], f(p)) for p in points))

which returns:

res = [((1, 2), (3, 4)), ((1, 2), (3, 5)), ((1, 2), (4, 5)), ((1, 3), (2, 4)), ((1, 3), (2, 5)), ((1, 3), (4, 5)), ((1, 4), (2, 3)), ((1, 4), (2, 5)), ((1, 4), (3, 5)), ((1, 5), (2, 3)), ((1, 5), (2, 4)), ((1, 5), (3, 4)), ((2, 3), (1, 4)), ((2, 3), (1, 5)), ((2, 3), (4, 5)), ((2, 4), (1, 3)), ((2, 4), (1, 5)), ((2, 4), (3, 5)), ((2, 5), (1, 3)), ((2, 5), (1, 4)), ((2, 5), (3, 4)), ((3, 4), (1, 2)), ((3, 4), (1, 5)), ((3, 4), (2, 5)), ((3, 5), (1, 2)), ((3, 5), (1, 4)), ((3, 5), (2, 4)), ((4, 5), (1, 2)), ((4, 5), (1, 3)), ((4, 5), (2, 3))]

It basically boils down to itertools.combinations (which you already did) with itertools.product. The twist is the filtering performed between the two (see f = lambda ...). If you need further assistance understanding the code, let me know.

Ma0
  • 15,057
  • 4
  • 35
  • 65