Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Array Unexpected Overwrite

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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. Look up the copy module in python.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading