簡體   English   中英

2D二進制列表python

[英]2D binary list python

我在制作將數字放在二進制網格內的函數時遇到麻煩。 例如,如果給定4 3 2 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:

聽起來,如果您可以創建一個具有原點原點(row, column)和大小block的正方形,而不會超出范圍或與任何非零元素重疊,則isSpaceFree應該返回True 在這種情況下,您的工作距離就是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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM