2017-07-11 37 views
-1

當我在codewars中輸入我的代碼時,我得到這個錯誤。 「回溯:模塊 中的damaged_or_sunk IndexError:列表索引超出範圍」。但是,當我在spyder3中嘗試我的代碼時,它工作得很好。雖然沒有關於這個錯誤在函數damaged_or_sunk中的位置的指示器。字符串索引必須是整數戰艦codewars kata

def damaged_or_sunk (board, attacks):   
    a = sum(x.count(1) for x in board) 
    b = sum(x.count(2) for x in board) 
    c = sum(x.count(3) for x in board) 
    a1 = 0 
    b1 = 0 
    c1 = 0    
    points = 0 
    sunk = 0 
    damaged = 0 
    not_touched = 0 


    for each in attacks: 
     rand_row = each[0] 
     rand_col = each[1] 

     if board[rand_row][rand_col] == 1: 
      a1 += 1 
     elif board[rand_row][rand_col] == 2: 
      b1 += 1 
     elif board[rand_row][rand_col] == 3: 
      c1 += 1 
     else: 
      pass 

    if a1 == a: 
     points += 1 
     sunk += 1 
    elif a1 == 0: 
     points -= 1 
     not_touched += 1 
    else: 
     points += 0.5 
     damaged += 1 

    if b1 == b: 
     points += 1 
     sunk += 1 
    elif b1 == 0: 
     points -= 1 
     not_touched += 1 
    else: 
     points += 0.5 
     damaged += 1 

    if c1 == c: 
     points += 1 
     sunk += 1 
    elif c1 == 0: 
     points -= 1 
     not_touched += 1 
    else: 
     points += 0.5 
     damaged += 1  

    return '{\'sunk\': %s, \'damaged\': %s, \'not_touched\': %s, \'points\': %s}' %(sunk, damaged, not_touched, points) 
+0

哪條線是錯誤?請提供[mcve]。 – Julien

+0

它不會打印回CodeWars上發生錯誤的地方。它只是說,在模塊中。 spyder3沒有錯誤發生 –

+0

如何構建'攻擊'?任何代碼示例? –

回答

0

attacks夫婦包含(x, y)座標必須是列表索引。

我做,他們是隨機生成的假設,確保:

  • 0 <= x < len(board[0])
  • 0 <= y < len(board)
  • all(len(board[0]) == len(board[row]) for row in board)
相關問題