1

If I already appended something in lista_input, whenever the parameter arr is modified inside the generabinario() method (for instance: arr[I] = 0/1) also all the values in lista_input are modified in the exact same way.

What is going on?

That's my output for the given program:

[[1, 1], [1, 1], [1, 1], [1, 1]]

Of course the output is a sequence of [1, 1] because it's the last modification that the method does to the arr paramater.

And that's the code:

lista_input = []

def generabinario(n, arr, i):
    if i == n:
        lista_input.append(arr)
        return
    arr[i] = 0
    generabinario(n, arr, i + 1)
    arr[i] = 1
    generabinario(n, arr, i + 1)


if __name__ == "__main__":
    weights = []
    results = []
    print("Inserisci il numero di pesi da inserire")
    num = int(input())
    print("Inserisci i pesi")
    for i in range(0, num):
        weights.append(int(input()))
    inputs = [None] * num
    generabinario(2, inputs, 0)
    print(lista_input)
vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • 1
    just in case, replace `inputs = [None] * num` with `inputs = [None for _ in range(num)]` and run the code – sittsering Oct 10 '21 at 16:36
  • 1
    You are appending the same `arr` each time, and then modifying it later, so all references update. Did you mean: `lista_input.append(arr[:])`? This appends a unique copy of `arr` each time. – quamrana Oct 10 '21 at 16:37
  • @quamrana Ty, that solved my problem! – huecraft341 Oct 10 '21 at 16:43

1 Answers1

0

Try:

lista_input = []

def generabinario(n, arr, i):
    if i == n:
        lista_input.append(arr[:])  # notice the arr[:]
        return
    arr[i] = 0
    generabinario(n, arr, i + 1)
    arr[i] = 1
    generabinario(n, arr, i + 1)


if __name__ == "__main__":
    weights = []
    results = []
    print("Inserisci il numero di pesi da inserire")
    num = int(input())
    print("Inserisci i pesi")
    for i in range(0, num):
        weights.append(int(input()))
    inputs = [None] * num
    generabinario(2, inputs, 0)
    print(lista_input)

The arr[:] creates a completely new array instead of having "different" arrays with the same reference. Using only arr, the same array is used at every call since they all have the same reference (ie the same emplacement in memory). By modifying one array, you are modifying this emplacement and therefore modifying all the arrays that point to this emplacement.

See this answer on another question to see what value and reference are and the behaviours associated with it: https://stackoverflow.com/a/986145/5446749

vvvvv
  • 25,404
  • 19
  • 49
  • 81