I have a list (say 6 elements for simplicity)
L = [0, 1, 2, 3, 4, 5]
and I want to chunk it into pairs in ALL possible ways. I show some configurations:
[(0, 1), (2, 3), (4, 5)] [(0, 1), (2, 4), (3, 5)] [(0, 1), (2, 5), (3, 4)]
and so on. Here (a, b) = (b, a)
and the order of pairs is not important i.e.
[(0, 1), (2, 3), (4, 5)] = [(0, 1), (4, 5), (2, 3)]
The total number of such configurations is 1*3*5*...*(N-1)
where N
is the length of my list.
How can I write a generator in Python that gives me all possible configurations for an arbitrary N
?
To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.
Take a look at itertools.combinations
.
matt@stanley:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> list(itertools.combinations(range(6), 2)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With