如何使用for循环检查电路板中的所有值是否已满

2024-04-29 00:47:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码来定义一个小电路板:

w= 2
h= 2
board = [[0] * h for i in range(w)]
def printboard():
    for row in board:
        print("  ".join([str(cell) for cell in row]))

现在我想定义一个函数,它将在board[0][0]!=0 and board[0][1]!=0 and board[1][0]!=0 and board[1][1]!=0时打印“board is full”

我的代码无效:

def checkfortie():
    for i in range(w-1):
        for j in range(h-1):
            if board[i][j]!=0:
                print("It's a tie!")

即使只有board[0][0]=1board[1][0]=1,代码也会打印出一条领带。有人能解释一下为什么没用吗?你知道吗


Tags: and代码inboardfor定义defcell
2条回答

对于检查领带,最好检查未归档元素的第一种情况。这样做将允许您在确定支票不是平局时立即停止支票。用另一种方法做需要每次迭代整个电路板。你知道吗

def checkfortie():
    for row in board:
       for square in row:
           if square == 0:
               return False # once you have found a single tile not filled, you can stop checking

    return True # loop completed without finding an open tile


if checkfortie():
   print("It's a tie")

你的意图是集体地检查它们,但是相反,你是单独地检查每一个。你知道吗

试试这样的。这里有一个解决方案,我尽可能少地修改你的代码。你知道吗

def checkfortie():
    tie = True
    for i in range(w):
        for j in range(h):
            if board[i][j] == 0:
                tie = False
    if tie:
        print("It's a tie!")

更简单的方法可能是展平阵列:

def checkfortie():
    return all(x == 1 for row in board for x in row)

if (checkfortie()):
    print("It's a tie!")

注意,在您的原始代码中,您将从w和h中减去1。这不是必需的,实际上是在产生问题。尝试运行以下命令:

for i in range(w-1):
    for j in range(h-1):
        print(i, j)

你会看到它只打印0,0

for i in range(w):
    for j in range(h):
        print(i, j)

将打印上述代码

0 0
0 1
10
1 1

相关问题 更多 >