我在做一个在二进制网格中放置一个数字的函数时遇到了困难。例如,如果给我432.1,并且我有一个5x5的网格,它看起来就像.
4 4 4 4 1
4 4 4 4 0
4 4 4 4 0
4 4 4 4 0
0 0 0 0 0 我的当前代码读取一个文本文件,并创建一个按降序排列的列表。例如,如果文本文件包含1 2 3,它将创建一个整数列表3 2 1。我的代码还提示输入一个bin #,它创建了binxbin正方形。我不知道怎么把垃圾箱放在4号里。这是一个函数,应该放在我一直坚持的值中。
def isSpaceFree(bin, row, column, block):
if row + block > len(bin):
return False
if column + block > len(bin):
return False
if bin[row][column] == 0 :
return True
else:
return False
for r in range(row, row+block):
if bin[row][column] != 0:发布于 2013-10-22 15:29:11
听起来isSpaceFree应该返回True,如果您可以创建一个具有原点(row, column)和大小block的正方形,而不超出界限或重叠任何非零元素。在这种情况下,你有75%的路要去。您已经准备好了边界检查,并完成了一半的重叠检查循环。
def isSpaceFree(bin, row, column, block):
#return False if the block would go out of bounds
if row + block > len(bin):
return False
if column + block > len(bin):
return False
#possible todo:
#return False if row or column is negative
#return False if the square would overlap an existing element
for r in range(row, row+block):
for c in range(column, column+block):
if bin[r][c] != 0: #oops, overlap will occur
return False
#square is in bounds, and doesn't overlap anything. Good to go!
return True然后,实际上放置块是相同的双嵌套循环,而是执行赋值。
def place(bin, row, column, block):
if isSpaceFree(bin, row, column, block):
for r in range(row, row+block):
for c in range(column, column+block):
bin[r][c] = block
x = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
]
place(x, 0, 0, 4)
print "\n".join(str(row) for row in x)结果:
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[0, 0, 0, 0, 0]https://stackoverflow.com/questions/19521643
复制相似问题