-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