简体   繁体   中英

Find all combinations to split a single list into two lists

I have a list which contains few number of elements and I'd like to find all possibilities to split this list into two list.

I mean, all combinations mean I wouldn't care about its element order. ie if element 2 and 3 are in the one list, element 1 in the other. ([2,3],[1]) == ([1],[2,3])

Here is what I tried:

import itertools

input_list = [10, 5, 15, 20, 25]
subset1, subset2, subsets = [], [], []


#sort input list
stuff = list(input_list)
stuff.sort()

#Find all possible [0] positions of given list
for L in range(0, len(stuff)+1):
    for subset in itertools.permutations(stuff, L):
        temp1 = list(subset)
        temp1.sort()
        if temp1 not in subset1:
            subset1.append(list(temp1))

#find all possible [1] positions 
for L2 in range(len(subset1)):
    temp2 = list( set(stuff) - set(subset1[L2]))
    temp2.sort()
    subset2.append(temp2)

#combine two position lists and filter out same combination  
for L3 in range(len(subset1)):
    temp3 = [subset1[L3],subset2[L3]]

    temp3.sort()

    #filter out same combination result but different order
    if temp3 not in subsets:
        subsets.append(temp3)

When I ran this code, I found out few number of my subsets list's elements contain unexpected tuple data, like [[5, 25], [10, 15, 20], ([5, 15, 25], [10, 20])].

I'm totally confused where those tuple type data is came from. Could someone point out thing what I missed?

Thank you

When I execute your code, I get the output

[[[], [5, 10, 15, 20, 25]], [[5], [10, 15, 20, 25]], [[5, 15, 20, 25], [10]], [[5, 10, 20, 25], [15]], [[5, 10, 15, 25], [20]], [[5, 10, 15, 20], [25]], [[5, 10], [15, 20, 25]], [[5, 15], [10, 20, 25]], [[5, 20], [10, 15, 25]], [[5, 25], [10, 15, 20]], [[5, 20, 25], [10, 15]], [[5, 15, 25], [10, 20]], [[5, 15, 20], [10, 25]], [[5, 10, 25], [15, 20]], [[5, 10, 20], [15, 25]], [[5, 10, 15], [20, 25]]]

without any tuples in it. One simpler solution using itertools could be

def two_partitions(S):
    res_list = []
    for l in range(0,int(len(S)/2)+1):
        combis = set(itertools.combinations(S,l))
        for c in combis:
            res_list.append((sorted(list(c)), sorted(list(S-set(c)))))
    return res_list

two_partitions({10, 5, 15, 20, 25})

You may or may not need the sorting of the sublists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM