蟒蛇:错误类型和指数误差(2.7.6)
问题描述:
我是相当新的蟒蛇,我在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]的行。 请帮忙!谢谢。
答
编辑:此回复是针对问题代码的较早版本。
假设所有的代码应该是放克以内():
您需要终止while循环一次toCheck是空的。在您弹出所有值后,原始版本尝试索引空列表。试试这个:
# loop 4 way check
while len(toCheck) > 0:
#store and pop current element
i = toCheck[0][0]
j = toCheck[0][1]
toCheck.pop(0)
此外,您不需要在添加值之前声明toCheck。您可以更换
toCheck = [[],[]]
toCheck.append([x,y])
随着
toCheck = [x, y]
+0
仍然会出现类型错误 – ericstevens26101
格式的代码缩进正确 – donkopotamus
在代码中,'funk'不会被调用,并没有为'是不断提供population'值。请阅读[如何创建一个最小,完整和可验证的示例](http://*.com/help/mcve)并适当地更新您的问题。 – John1024
你在'toCheck.append([x,y])'之后期望'toCheck'的状态是什么? – donkopotamus