我正在为一项作业的黑盒测试编写代码。在我的函数中,输入是一个2d数组,int表示x,int表示y,int表示僵尸强度。从我的起始位置开始,如果元素的值小于僵尸强度,我将元素的值更改为-1。然后我得到了元素,上,下,左,右(不是对角线),并对它们做同样的处理。我使用的是try except,如果元素存在,则将其添加到列表中,如果不存在,则继续。据我所知,使用try except将停止添加列表中数组中不存在的元素。这就是为什么我不确定为什么在黑盒测试代码时会出现索引错误。我添加了输入,但我不知道黑盒测试使用的是什么输入。你知道吗
Here is my code
population = [[9, 3, 4, 5, 4], [1, 6, 5, 8, 9], [2, 3, 7, 3, 2], [4,5,1,4,3], [4, 5, 4, 3, 9]]
x = 2
y = 1
zombie = 5
def answer(population, x, y, zombie):
list = []
list.append([x,y])
while list:
print list
front_of_list = list.pop(0)
x = front_of_list[0]
y = front_of_list[1]
if population[front_of_list[0]][front_of_list[1]] <= zombie and population[front_of_list[0]][front_of_list[1]] >= 0:
population[front_of_list[0]][front_of_list[1]] = -1
if x-1 >=0:
try:
population[x-1][y]
list.append([x-1,y])
except:
pass
if y-1 >= 0:
try:
population[x][y-1]
list.append([x,y-1])
except:
pass
if x+1 < len(population):
try:
population[x+1][y]
list.append([x+1,y])
except:
pass
if y+1 < len(population[0]):
try:
population[x][y+1]
list.append([x,y+1])
except:
pass
answer(population, x, y, zombie)
print population
您的
try
子句不是必需的,因为您之前所做的if
测试涵盖了这种情况。让我们试着简化和澄清代码,看看这是否解决了您的问题,因为我们无法直接复制它。你知道吗首先,当
x
和y
可以使用时,您继续使用front_of_list
;我们可以通过组合测试简化if
子句(Python特性);(x, y)
是自然元组,因此我将它们切换;您重新定义了内置名称list
,因此我将其切换为array
;最后,我将测试简化为循环,以减少复制粘贴错误的机会。这给我们留下了:将此插入到测试环境中,如果继续失败,则传递准确的错误消息。你知道吗
你的代码和这个假设一个矩形矩阵,如果你的二维数组是参差不齐的,这将导致一个索引错误。(需要仔细检查的东西。)
更新
传统意义上的x是列,y是行,但您的代码(和我的返工)却相反。在内部,这没有什么区别,但由于您被作为参数传递x&y,从您插入的代码的角度来看,这可能意味着起点不正确,并可能导致结果无效。(再说一遍,要仔细检查一下。)
相关问题 更多 >
编程相关推荐