Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Well... Let's try to be lazy, and reuse work already done :

sage: subsets?
Docstring:     
   Iterator over the *list* of all subsets of the iterable X, in no
   particular order. Each list appears exactly once, up to order.

   INPUT:

   * "X" - an iterable

   OUTPUT: iterator of lists

So, what's wrong with :

sage: [u for u in subsets(ListA) if len(u) == 2]
[[1, 2], [1, 3], [2, 3]]

Of course, the subsets operator will generate all subsets of ListA. It might be interesting to write a specialized generator...

OTOH, someone already did the work (and probably better than I can do) :

sage: Subsets?
Docstring:     
   Return the combinatorial class of the subsets of the finite set
   "s". The set can be given as a list, Set or any iterable
   convertible to a set. Alternatively, a non-negative integer n can
   be provided in place of "s"; in this case, the result is the
   combinatorial class of the subsets of the set \{1,2,...,n\} (i.e.
   of the Sage "range(1,n+1)").

   A second optional parameter "k" can be given. In this case,
   "Subsets" returns the combinatorial class of subsets of "s" of size
   "k".

Therefore :

sage: list(Subsets(ListA, 2))
[{1, 2}, {1, 3}, {2, 3}]

Beware : the returned elements are Sets (and not sets). If you insist on lists :

sage: list(map(list, Subsets(ListA, 2)))
[[1, 2], [1, 3], [2, 3]]

HTH,