I'm trying to make a function that takes an array of numbers and gives you every combination those numbers can be in, in two arrays.
My problem is that I can print the exact results that I want, but when I try to save the results into a variable, for some reason, I get the same sub-array spammed in my array.
Here is the code:
test = []
def partitioner(array1, array2):
a = array1
b = array2
for _ in range(len(b)):
a.append(b[0])
del b[0]
if(len(b) >= 1 and len(a) >= 1):
print([a, b]) # This part right here, I'm printing the expected
test.append([a, b]) # But this array is getting the actual
partitioner(a, b)
b.append(a[-1])
del a[-1]
partitioner([], [x for x in range(3)])
print(test)
Expected:
[
[[0], [1, 2]],
[[0, 1], [2]],
[[0, 2], [1]],
[[1], [2, 0]],
[[1, 2], [0]],
[[1, 0], [2]],
[[2], [0, 1]],
[[2, 0], [1]],
[[2, 1], [0]]]
Actual:
[
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]]]
a
and b
are lists, so when they are overridden every iteration of the recursion with the last value it changes the values in test
as well. Append a copy of a
and b
instead
test.append([a[:], b[:]])