-1

I'm trying to write a function in python that returns the powerset of a list inputted to it. In lines 5 and 6, I try to append an element to only the second half of the array but it apparently gets appended to all the elements of the array. Why does this happen and how can I fix it?

Code:

def powerset(array):
    ans=[[]]
    for elem in array:
        ans.extend(ans.copy())
        for j in range(int(len(ans)/2), len(ans)):
            ans[j].append(elem)
    return ans

Example input: [0, 1]

Output returned by above function: [[0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1]]

Expected Output: [[], [0], [1], [0, 1]]

Mathphile
  • 185
  • 1
  • 9
  • 2
    `ans.copy()` creates a *shallow copy*. You would need `ans.extend([x.copy() for x in ans])` – juanpa.arrivillaga Sep 06 '21 at 06:14
  • 1
    Or You can use `deepycopy` from `copy` module. – Abdul Niyas P M Sep 06 '21 at 06:15
  • Just a short remark: Python does have both the datatype [`list`](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) and [`array`](https://docs.python.org/3/library/array.html). These should not be clearly distinguished from each other. – albert Sep 06 '21 at 06:17

1 Answers1

1

You're making a shallow copy of ans, means the elements inside the list in ans are not copied, they remain the same.

Use copy.deepcopy().

from copy import deepcopy

def powerset(array):
    ans=[[]]
    for elem in array:
        ans.extend(deepcopy(ans))
        for j in range(int(len(ans)/2), len(ans)):
            ans[j].append(elem)
    return ans

print(powerset([0, 1]))

Output:

[[], [0], [1], [0, 1]]
bereal
  • 32,519
  • 6
  • 58
  • 104