2014-05-23 38 views
2

我想實現的算法,但要得到一個錯誤,我不知道是什麼原因:獲取類型錯誤:列表索引必須是整數,而不是元組

size = len(data) 
total = sum(data) 

barray = [[False for x in range(int(size+1))] for x in range(int((total/2)+1))] 

for x in range(0,size): 
    barray[0][x] = True 

for x in range(1,int(total/2)): 
    barray[x][0] = True 

for i in range(1,int(total/2)): 
    for j in range(1,size): 
     barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1] 

return barray[int(total/2),size] 

錯誤:

Traceback (most recent call last): 
File "C:/Users/tuf21741/PycharmProjects/PyBackup/test.py", line 25, in <module> 
assert checkio([10, 10]) == 0, "1st example" 
File "C:/Users/tuf21741/PycharmProjects/PyBackup/test.py", line 17, in checkio 
barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1] 
TypeError: list indices must be integers, not tuple 
+1

' 'B [I,J]'!= 'B [i] [j]''使用時numpy的(或類似的)陣列 – jonrsharpe

+0

這(在OPS)語法是唯一正確的。 –

+0

[Python的列表索引必須是整數,而不是元組的「可能的重複」(http://stackoverflow.com/questions/9367813/python-list-indices-must-be-integers-not-tuple-error) –

回答

2
barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1] 

看起來你應該在這裏爲你的索引使用單獨的方括號。

barray[i][j] = (barray[i][j - 1] or barray[i - data[j - 1]][j - 1]) if data[j-1] <= i else barray[i][j - 1] 

並且對於return語句也是如此。

return barray[int(total/2)][size] 
相關問題