首页 > 解决方案 > 在 Python 中编写一个“棋盘”函数,打印出请求的二进制长度

问题描述

我有一个我正在努力解决的 Python 课程的作业。

我们应该创建一个打印出二进制文件的函数,如下所示:

如果输入是:

chessboard(3)

它应该打印出来:

101
010
101

等等..

它是一个“简单”的程序,但我对编码真的很陌生。

我可以生成一个 while 循环来写出正确的行长和行数,但我很难在行之间产生变化。

到目前为止,这是我想出的:

def chessboard(n):
height = n
length = n
while height > 0:
    while length > 0:
        print("1", end="")
        length -= 1
        if length > 0:
            print("0", end="")
            length -= 1
    height -= 1
    if length == 0:
        break
    else:
        print()
        length = n

输入:

chessboard(3)

它打印出来:

101
101
101

有人可以帮我弄清楚如何以零而不是一开始每隔一行吗?

标签: pythonfunctionif-statementwhile-loopbinary

解决方案


据我了解,这很简单:

print("stackoverflow")

def chessboard(n):
    finalSentence1 = ""
    finalSentence2 = ""
    for i in range(n): #we add 0 and 1 as much as we have n
        if i%2 == 0: #
            finalSentence1 += "1"
            finalSentence2 += "0"
        else:
            finalSentence1 += "0"
            finalSentence2 += "1"


    for i in range(n): #we print as much as we have n
        if i%2 == 0:
            print(finalSentence1)
        else:
            print(finalSentence2)



chessboard(3)

返回:

stackoverflow
101
010
101

推荐阅读