如何使嵌套列表的行为类似于numpy数组?

时间:2020-11-07 13:49:32

标签: python arrays numpy

我正在尝试实现一种算法来计算python中具有给定总和的子集

import numpy as np 
  
maxN = 20
maxSum = 1000
minSum = 1000
base = 1000
dp = np.zeros((maxN, maxSum + minSum))
v = np.zeros((maxN, maxSum + minSum)) 
# Function to return the required count  
def findCnt(arr, i, required_sum, n) : 
    # Base case  
    if (i == n) : 
        if (required_sum == 0) : 
            return 1
        else : 
            return 0
    # If the state has been solved before  
    # return the value of the state  
    if (v[i][required_sum + base]) : 
        return dp[i][required_sum + base]
    # Setting the state as solved  
    v[i][required_sum + base] = 1
    # Recurrence relation  
    dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n)
    return dp[i][required_sum + base]
  
arr = [ 2, 2, 2, 4 ]  
n = len(arr) 
k = 4
  
print(findCnt(arr, 0, k, n))

它给出了预期的结果,但是我被要求不要使用numpy,所以我用这样的嵌套列表替换了numpy数组:

#dp = np.zeros((maxN, maxSum + minSum)) replaced by
dp = [[0]*(maxSum + minSum)]*maxN
#v = np.zeros((maxN, maxSum + minSum)) replaced by
v = [[0]*(maxSum + minSum)]*maxN

但是现在程序总是在输出中给我0,我认为这是由于numpy数组和嵌套列表之间的某些行为差异,但是我不知道如何解决它

编辑:

感谢@venky__在评论中提供了此解决方案:

[[0 for i in range( maxSum + minSum)] for i in range(maxN)]

它起作用了,但是我仍然不明白它与以前所做的事情有什么区别,我尝试过:

print( [[0 for i in range( maxSum + minSum)] for i in range(maxN)] == [[0]*(maxSum + minSum)]*maxN )

结果是True,那么这如何解决问题?

1 个答案:

答案 0 :(得分:0)

事实证明,我使用嵌套列表表示二维数组的方式不正确,因为python并未创建单独的objets,但是相同的子列表索引引用了相同的整数对象,有关详细说明,请阅读{{3 }}。