-2
我是相當新的蟒蛇,我在2.7.6有一個問題,是不是在3.4.4蟒蛇:錯誤類型和指數誤差(2.7.6)
的代碼有問題:
def answer(population, x, y, strength):
# make sure Z is infectable
if population[x][y] > strength:
return population
else:
population[x][y] = -1
# get array dimentions
rows = len(population)
cols = len(population[0])
# declare checking array
toCheck = []
toCheck.append([x,y])
# loop 4 way check
while(1):
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
# left
if j != 0:
if population[i][j-1] <= strength and population[i][j-1] != -1:
population[i][j-1] = -1
toCheck.append([i,j-1])
# top
if i != 0:
if population[i-1][j] < strength and population[i-1][j] != -1:
population[i-1][j] = -1
toCheck.append([i-1,j])
# right
if j != cols-1:
if population[i][j+1] > strength and population[i][j+1] != -1:
population[i][j+1] = -1
toCheck.append([i,j+1])
# bottom
if i != rows-1:
if population[i+1][j] > strength and population[i+1][j] != -1:
population[i+1][j] = -1
toCheck.append([i+1][j])
if len(toCheck) == 0:
return population
給了我一個'TypeError'。雖然代碼:
def answer(population, x, y, strength):
# make sure Z is infectable
if population[x][y] > strength:
return population
else:
population[x][y] = -1
# get array dimentions
rows = len(population)
cols = len(population[0])
# declare checking array
toCheck = [[]]
toCheck.append([x,y])
# loop 4 way check
while(1):
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
# left
if j != 0:
if population[i][j-1] <= strength and population[i][j-1] != -1:
population[i][j-1] = -1
toCheck.append([i,j-1])
# top
if i != 0:
if population[i-1][j] < strength and population[i-1][j] != -1:
population[i-1][j] = -1
toCheck.append([i-1,j])
# right
if j != cols-1:
if population[i][j+1] > strength and population[i][j+1] != -1:
population[i][j+1] = -1
toCheck.append([i,j+1])
# bottom
if i != rows-1:
if population[i+1][j] > strength and population[i+1][j] != -1:
population[i+1][j] = -1
toCheck.append([i+1][j])
if len(toCheck) == 0:
return population
給我和'IndexError'。這兩個錯誤發生在i = toCheck [0] [0]的行。 請幫忙!謝謝。
格式的代碼縮進正確 – donkopotamus
在代碼中,'funk'不會被調用,並沒有爲'是不斷提供population'值。請閱讀[如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)並適當地更新您的問題。 – John1024
你在'toCheck.append([x,y])'之後期望'toCheck'的狀態是什麼? – donkopotamus