Home > Software design >  Python Array Unexpected Overwrite
Python Array Unexpected Overwrite

Time:11-30

i have a question about python list, I want to generate a array like (001, 002, 011, 012) when i try to add a list to list, a new list try to overwrite old element

n = 3
def setNextCombination(P):
    idx = len(P) - 1
    while True:       
        if idx == 0:
            break
        if P[idx] < idx:
            P[idx]  = 1
            curr = idx   1
            while curr < len(P):
                P[curr] = P[idx]
                curr  = 1
            return P, True
        idx -= 1
    return [], False

def path_choosing():
    P = np.zeros(n, dtype=int)
    flag = True
    arr = [0,0,0,0]
    idx = 0
    while True:
        P, flag = setNextCombination(P)
        if(flag == False): break
        arr[idx] = P
        idx  = 1
        print(idx)
        print(arr)
path_choosing()

Actual Output:

1
[array([0, 0, 1]), 0, 0, 0]
2
[array([0, 0, 2]), array([0, 0, 2]), 0, 0]
3
[array([0, 1, 1]), array([0, 1, 1]), array([0, 1, 1]), 0]
4
[array([0, 1, 2]), array([0, 1, 2]), array([0, 1, 2]), array([0, 1, 2])]

My excepted output

1
[array([0, 0, 1]), 0, 0, 0]
2
[array([0, 0, 1]), array([0, 0, 2]), 0, 0]
3
[array([0, 0, 1]), array([0, 0, 2]), array([0, 1, 1]), 0]
4
[array([0, 0, 1]), array([0, 0, 2]), array([0, 1, 1]), array([0, 1, 2])]

i dont know how, please help me

CodePudding user response:

P = np.zeros(n, dtype=int)

This is where you created a numpy array in memory. You're passing a reference to this array, 'P', to the setNextCombination method, and that makes changes to it. You never actually create a new array in memory, so when you do arr[idx] = P, you're pointing to the same array in memory every time.

You should pass a copy of your np array to setNextCombination instead. You could use numpy.copy for this. Alternatively, look up the copy module in python.

  • Related