Split a list into two sublists in all possible ways

前端 未结 4 962
情深已故
情深已故 2020-12-08 22:42

I have a list of variable size, for example

[1, 2, 3, 4]

and I want to get every possible way to split this list into two:

         


        
4条回答
  •  醉梦人生
    2020-12-08 23:11

    A more low-level solution using bitwise arithmetic to count subsets that should be easy to translate to Java:

    def sublists(xs):
        l = len(xs)
        for i in range(1 << l):
            incl, excl = [], []
            for j in range(l):
                if i & (1 << j):
                    incl.append(xs[j])
                else:
                    excl.append(xs[j])
            yield (incl, excl)
    

提交回复
热议问题