我有一个不会破坏的while循环。我添加了一个冗余的条件,以使其中断,但这也不起作用。它应该循环通过一个2d数组,看看它是否可以在该位置放置一定尺寸的块。块是列表,框是2d列表。这是整个计划。有问题的函数是fillBox
def makeBox(dim):
box = [[0 for x in range(0, dim)] for y in range(0, dim)]
return box
def printBox(lst):
for x in lst:
print(x)
print()
def isSpaceFree(box, row, col, block):
isFree = True
if block > 1:
if row+block-1 < len(box) and col+block-1 < len(box):
for x in range(row,row+block):
for y in range(col, col+block):
if box[x][y] != 0:
isFree = False
else:
isFree = False
elif block == 1:
if box[row][col] == 0:
isFree = True
else:
isFree = False
return isFree
def fillSpace(block, row, col, box):
if block > 1:
for x in range(row, row + block):
for y in range(col, col + block):
box[x][y] = block
if block == 1:
box[row][col] = block
printBox(box)
def fillBox(block, box):
row = 0
col = 0
while len(block) > 0:
if len(block) == 0:
break
if row == len(block):
col = 0
row = 0
block.pop(0)
if col == len(block):
col = 0
row += 1
if isSpaceFree(box, row, col, block[0]):
fillSpace(block[0], row, col, box)
block.pop(0)
row = 0
col = 0
continue
col += 1
def main():
dim = int(input("Enter box dimension: "))
file = open(input("Block File: "))
blocks = []
for x in file:
blocks = x.split()
for x in range(0,len(blocks)):
blocks[x] = int(blocks[x])
blocks.sort(reverse=True)
box = makeBox(dim)
fillBox(blocks, box)
printBox(box)
main()
答案 0 :(得分:1)
循环中的第一个条件永远不会被触发。
如果块大于零(继续循环),它就不会等于零。
答案 1 :(得分:1)
if row == len(block):
col = 0
row = 0
block.pop(0) # If row == 1 and len(block) == 1 This will pop the last item
if col == len(block):
col = 0
row += 1
if isSpaceFree(box, row, col, block[0]): # Then this index will be out of bounds - correct?