2012-09-21 36 views
0

考慮蟒蛇下面的代碼:Python列表尺寸大小錯誤

def main(): 
    n = input() 
    s = input() 

    coins = [ 0 ]*n 
    dp = [ 0 ]*(s+1) 

    print coins 
    print dp 

    for i in range(n) : 
     coins[ i ] = input() 

    dp[ 0 ]=0 
    dp[ 1 ]=1 

    for i in range(2, s+1) : 
     min_val = 999999 
     for j in range(0, n) : 
      if i-coins[ j ] > 0 : 
       if dp[ i-coins[ j ] ] + 1 < min_val : 
        min_val = dp[ i-coins[ j ] ] + 1 


    print coins 
    print dp 

    print coins[ s ] 

if __name__ == "__main__" : 
    main() 

當我編譯並運行這個程序,我得到以下運行時錯誤:

File "test.py", line 33, in <module> 
    main(); 
File "test.py", line 30 in main 
    if dp[ i-coins[ j ] ] + 1 < min_val : 

IndexError: list index out of range 

這有什麼錯呢?

輸入:

5 10 
1 3 5 7 9 
+2

你不*需要在Python中使用';'分號。它們只會增加噪音。 –

+0

鑑於您已經在上面的行中使用了'coins [j]'這個表達式,那不可能是。嘗試打印該表達式的值。 –

+2

你爲什麼要導入'array'?你沒有使用該模塊中的任何功能。 –

回答

1

嘗試使用

coins = [ 0 ]*n 
dp = [ 0 ]*(s+1) 

給init陣列。

File "ttt.py", line 31, in <module> 
    main() 
    File "ttt.py", line 21, in main 
    if dp[ i-coins[ j ] ] + 1 < min_val : 
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 

print dp[s]而非print coins[s]最後一行:

我在我的機器上有一個總不同的錯誤。

+0

正確,但仍然有錯誤。 –

+0

@RondogiannisAristophanes,我添加了一個換行符... – Marcus

+0

非常感謝! –

0

DP爲s + 1米的長度,但你的for循環去到n。如果s + 1> n那麼這將工作。但在這種情況下,我認爲你的s + 1 < n。

dp = [ None ]*(s+1); # dp is s+1 in length. 

for j in range(0, n) # loop goes to n. 

列表索引超出範圍意味着S + 1 <Ñ

1

我們知道(從上一行if),該i-coins[ j ] > 0,所以它必須大於或等於len(dp),其是s + 1i小於s+1,所以coins[ j ]是負數。

您是否爲coins之一輸入負數?

+0

不,我沒有... –