Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sorted combinations

I have a input like

A = [2,0,1,3,2,2,0,1,1,2,0].

Following I remove all the duplicates by

A = list(Set(A))

A is now [0,1,2,3]. Now I want all the pair combinations that I can make with this list, however they do not need to be unique... thus [0,3] equals [3,0] and [2,3] equals [3,2]. In this example it should return

[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]]

How do I achieve this? I looked in the iteratools lib. But couldn't come up with a solution.

like image 542
WGL Avatar asked Apr 06 '11 01:04

WGL


1 Answers

>>> A = [2,0,1,3,2,2,0,1,1,2,0]
>>> A = sorted(set(A))   # list(set(A)) is not usually in order
>>> from itertools import combinations
>>> list(combinations(A, 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

>>> map(list, combinations(A, 2))
[[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]

>>> help(combinations)
Help on class combinations in module itertools:

class combinations(__builtin__.object)
 |  combinations(iterable, r) --> combinations object
 |  
 |  Return successive r-length combinations of elements in the iterable.
 |  
 |  combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  next(...)
 |      x.next() -> the next value, or raise StopIteration
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
like image 173
John La Rooy Avatar answered Nov 14 '22 22:11

John La Rooy