-1

Hi I'm trying to make a list of all possible cohesive combinations of another list, so from [0, 1, 2, 3] I'd like to get [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]. So far I've got this:

def expandArray(arr):
    result = []
    for x in range(0, len(arr)):
        subArray = [arr[x]]
        result.append(subArray)
        for y in range(x + 1, len(arr)):
            subArray.append(arr[y])
            result.append(subArray)
    return(result)

But this returns: [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3], [2, 3], [3]].

What am I doing wrong ?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Snakey
  • 3
  • 1
  • possible duplicate of [What's a good way to get all subsets of a set?](https://stackoverflow.com/questions/1482308/whats-a-good-way-to-get-all-subsets-of-a-set-powerset) – D. Jones Oct 18 '18 at 14:59
  • It looks like you are trying to create a 'Power Set' https://stackoverflow.com/questions/1482308/whats-a-good-way-to-get-all-subsets-of-a-set-powerset – user78090 Oct 18 '18 at 14:59
  • No Snakey does not seem to get sublists with "holes" in them. So [0, 3] should not be included in the result. – Moberg Oct 18 '18 at 15:01

2 Answers2

0

subArray is a list that you modify in your for loop. When you append to it, you do not create a new list, but you modify it, and then put it in the list again, so will in the end get a result with several copies of the same list. Compare this code:

a = []
b = [5]
a.append(b)
b.append(1)
a.append(b)

print(a)

would output:

[[5, 1], [5, 1]]
Moberg
  • 5,253
  • 4
  • 38
  • 54
0

Here is a way to have your desired output using list slicing:

def get_combs(iterable):
    for k, _ in enumerate(iterable):
        elm = k
        while elm <= len(iterable):
            data = iterable[k:elm]
            elm += 1
            if data:
                yield data

combs = list(get_combs([0, 1, 2, 3]))
print(combs)

Output:

[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43