0

Suppose I have a list of integers:

myList = [1,2,3,4]

How would one return every possible combination of these two subsets with Python.

For example, set [1,2,3,4] would produce [1,2], [3,4] and [1,3], [2,4] and [1,4],[2,3]

  • And if you intend on generating both pairs from each combination (I can't entirely tell from your question), see [How to split a list into pairs in all possible ways](http://stackoverflow.com/questions/5360220/how-to-split-a-list-into-pairs-in-all-possible-ways) for inspiration. – miradulo Aug 04 '16 at 11:24
  • Please see my edit for explanation as to why this is not a duplicate –  Aug 04 '16 at 12:26
  • "Every possible combination of these two subsets" doesn't make sense to me. Can you please add sample output? – miradulo Aug 04 '16 at 12:28
  • Please see my example input and output –  Aug 04 '16 at 12:35
  • Then what exactly do you expect for `[1, 2, 3, 4]`? All of the n choose 2 combinations are given by `itertools.combinations`, as linked in the duplicate.For instance for your `[1,2,3]` example, `list(combinations([1,2,3], 2))` produces `[(1, 2), (1, 3), (2, 3)]`. – miradulo Aug 04 '16 at 12:35
  • Sorry I explained that wrong. Please see my outputs now. It is now explained properly –  Aug 04 '16 at 12:39
  • Thank you for clarifying. Please see [this answer](http://stackoverflow.com/a/5362528/4686625) from the second question I linked, as well as [this recursive answer](http://stackoverflow.com/a/5360442/4686625). You could probably improve them, even. There's a few other approaches below those on the same question. – miradulo Aug 04 '16 at 12:42
  • This is actually still not what I mean. Suppose your list had 8 elements, we would return two sets each with 4 elements, then two sets with 4 elements in a different combination, etc until all combinations have been seen. We do not want to always return pairs –  Aug 04 '16 at 14:59
  • I ___really___ hope you're starting to see the importance of being clear with your question. Your question is effectively generating all `k`-subset partitions of equal size `i` for some `i` > 0 on an array `A`. Without the "equal size" restriction, this is a classical algorithm problem ([see here](http://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions)). Try and adapt it for your own purpose (the equality constraint) - it is too broad of a question to ask on Stack Overflow on its own anyways, it sounds an awful lot like homework. – miradulo Aug 04 '16 at 15:06

1 Answers1

-2

itertools can give you all combinations of a list of size you define (here n):

import itertools

myList = [1,2,3,4]
n=3
for subset in itertools.combinations(myList , n):
    print(subset)

output:

(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
Gal Dreiman
  • 3,969
  • 2
  • 21
  • 40