这是我应该做的:
Now, change your program so that it creates a grid with alternating 1s and 0s, in a checkerboard pattern, like this:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
HINT: You can use a single if statement inside
a doubly-nested for loop to do this. The if
statement I have in mind uses the % operator
and the sum of the row and column numbers.
这是我现在的代码:
Now, change your program so that it creates a grid with alternating 1s and 0s, in a checkerboard pattern, like this:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
HINT: You can use a single if statement inside
a doubly-nested for loop to do this. The if
statement I have in mind uses the % operator
and the sum of the row and column numbers.
这里是棋盘格,v1的说明:
在接下来的三个练习中,我们将努力创建一个程序,该程序在棋盘上存储与棋子相对应的数字!我们的最终目标是制作一个存储1和0的网格,如下所示,这样1代表棋盘格,0代表空白方块:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
请注意,中间两行为空白!
对于本练习,您应该仅创建一个在前3行和后3行中都有1的网格,这样看起来就这样:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
让我们尝试逐步进行此操作。
第1步:创建一个包含所有0的8x8网格。
第2步:将最上面的3行和所有最后3行都设为1。中间的两行应全为0。在将所有内容都设置为0后,应该执行此操作。
第3步:使用提供的print_board函数打印网格。 我有此练习的正确代码:
# Pass this function a list of lists, and it will
# print it such that it looks like the grids in
# the exercise instructions.
def print_board(board):
for i in range(len(board)):
# This line uses some Python you haven't
# learned yet. You'll learn about this
# part in a future lesson:
#
# [str(x) for x in board[i]]
print " ".join([str(x) for x in board[i]])
# Your code here...
for i in range(3):
print "1 1 1 1 1 1 1 1"
for i in range(2):
print "0 0 0 0 0 0 0 0"
for i in range(3):
print "1 1 1 1 1 1 1 1"
这是Checkerboard v3(我尚未尝试过):
现在,结合步骤3和4中的代码 制作一个在所有显示的空间中保持1s的网格 在上方的第一个网格中(每隔一个,但不包含1 中间两行)。
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
从代码中可以看到,我没有第二个for
循环或if
语句。我不知道该如何使用这两个代码。