首页 > 解决方案 > 算法覆盖 Numpy 数组元素,但不覆盖 Python 列表元素

问题描述

不久前,当我遇到这种奇怪的行为时,我一直在为 python 测试几种不同的排序算法。

使用从 GeeksforGeeks 复制的合并排序实现,我注意到我的 Numpy 数组被数组中的最后一个元素覆盖,而内置 Python 数组被正确排序。

这种行为的原因是什么?我有一种预感,它是由按引用传递与按值传递错误引起的,但我无法确定究竟是什么原因,因为它适用于内置的 python 数组。

注意:这种行为也发生在其他一些算法上,而不仅仅是归并排序。


这是一个可重现的示例:

import numpy as np

def mergeSort(arr):
    if len(arr) >1:
        mid = len(arr)//2 #Finding the mid of the array 
        L = arr[:mid] # Dividing the array elements  
        R = arr[mid:] # into 2 halves 

        mergeSort(L) # Sorting the first half 
        mergeSort(R) # Sorting the second half 

        i = j = k = 0
        # Copy data to temp arrays L[] and R[] 
        while i < len(L) and j < len(R): 
            if L[i] < R[j]: 
#                 print (arr, L, R)
                arr[k] = L[i]
#                 print (arr, L, R)
                i+=1
            else:
#                 print (arr, L, R)
                arr[k] = R[j] # Problem happens here, R replaces L and messes up calculations for numpy
#                 print (arr, L, R)
                j+=1
            k+=1

        # Checking if any element was left 
        while i < len(L): 
            arr[k] = L[i] 
            i+=1
            k+=1

        while j < len(R): 
            arr[k] = R[j] 
            j+=1
            k+=1

array = ([1,2,3,0])
print (f'python array before {array}')
mergeSort(array)
print (f'python array after {array}')

print ('----------')

array = np.array([1,2,3,0])
print (f'numpy array before {array}')
mergeSort(array)
print (f'numpy array after {array}')

这是控制台输出:

python array before [1, 2, 3, 0]
python array after [0, 1, 2, 3]
----------
numpy array before [1 2 3 0]
numpy array after [0 0 0 0]

我已将覆盖的位置缩小到以下行:

arr[k] = R[j]

您可以取消注释打印语句并在发生覆盖时查看覆盖:

python array before [1, 2, 3, 0]
[1, 2] [1] [2]
[1, 2] [1] [2]
[3, 0] [3] [0] <-- Before arr[k] = R[j]
[0, 0] [3] [0] <-- After arr[k] = R[j] -- OK
[1, 2, 3, 0] [1, 2] [0, 3]
[0, 2, 3, 0] [1, 2] [0, 3]
[0, 2, 3, 0] [1, 2] [0, 3]
[0, 1, 3, 0] [1, 2] [0, 3]
[0, 1, 3, 0] [1, 2] [0, 3]
[0, 1, 2, 0] [1, 2] [0, 3]
python array after [0, 1, 2, 3]
----------
numpy array before [1 2 3 0]
[1 2] [1] [2]
[1 2] [1] [2]
[3 0] [3] [0] <-- Before arr[k] = R[j]
[0 0] [0] [0] <-- After arr[k] = R[j] -- BAD
[1 2 0 0] [1 2] [0 0]
[0 2 0 0] [0 2] [0 0]
[0 2 0 0] [0 2] [0 0]
[0 0 0 0] [0 0] [0 0]
numpy array after [0 0 0 0]

转载:

Python 3.8.3 + Numpy 1.19.0

Jupyter Notebook 5.7.9 + Python 3.6.5 + Numpy 1.14.3

标签: pythonnumpy

解决方案


推荐阅读