All ways of partitioning a list into two non-empty lists

孤街浪徒 提交于 2021-01-28 10:12:53

问题


[0.0, 1.0, 2.0, 3.0, 4.0]

I have 5 numbers and two groups, left and right. Each number has two choices - it can go left or right. I need a list that contains all partitioning of the list [0,1,2,3,4] into two non empty parts. For example: [([0], [1,2,3,4]), ([0,1], [2,3,4]), ...,]

Note that there are a total of (2^5 -2)/2 partitioning - order doesn't matter and I don't want repeats. Meaning I don't want something like this (if my list was [1,2,3,4]):

[] [1, 2, 3, 4]
[1] [2, 3, 4]
[2] [1, 3, 4]
[1, 2] [3, 4]
[3] [1, 2, 4]
[1, 3] [2, 4]
[2, 3] [1, 4]
[1, 2, 3] [4]
[4] [1, 2, 3]
[1, 4] [2, 3]
[2, 4] [1, 3]
[1, 2, 4] [3]
[3, 4] [1, 2]
[1, 3, 4] [2]
[2, 3, 4] [1]
[1, 2, 3, 4] []

I've looked into all of the itertools functions and none seem to work.


Edit: for list [i for i in range(16)], which has 16 elements, If I do the following, this is what I see:

 n = len(l)//2 + 1
>>> xs = list(chain(*[combinations(l, i) for i in range(1, n)]))
>>> pairs = [(list(x), list(set(l) - set(x))) for x in xs]
>>> print len(pairs)
    39202
>>> (2**16-2)/2
    32767

In fact, it doesn't work for a list with 6 elements either. I don't see why...

The problem occurs for all even length lists. For example, when I try a length 2 list, I get:

[([0.0], [1.0]), ([1.0], [0.0])]


回答1:


The stuff is there in itertools, maybe you just weren't looking in the right places.

Here is teh codez:

from collections import OrderedDict
from itertools import chain, combinations

def partition(L):
    n = len(L)//2 + 1
    xs = chain(*[combinations(L, i) for i in range(1, n)])
    pairs = (tuple(sorted([x, tuple(set(L) - set(x))])) for x in xs)
    return OrderedDict.fromkeys(pairs).keys()

Output:

>>> for pair in partition([1,2,3,4]):
...     left, right = map(list, sorted(pair, key=len))
...     print left, right
...
[1] [2, 3, 4]
[2] [1, 3, 4]
[3] [1, 2, 4]
[4] [1, 2, 3]
[1, 2] [3, 4]
[1, 3] [2, 4]
[1, 4] [2, 3]


来源:https://stackoverflow.com/questions/36509227/all-ways-of-partitioning-a-list-into-two-non-empty-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!