在 Python 中编写一个 "Chessboard" 函数,打印出请求的二进制长度
Writing a "Chessboard" function in Python that prints out requested length of binary
我的 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
谁能帮我弄清楚如何以零而不是一个开始每一行?
据我了解,很简单:
print("Whosebug")
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)
returns :
Whosebug
101
010
101
我正在处理相同类型的赋值,但是到目前为止我们只介绍了条件语句和 while 循环,遵循相同的逻辑,这是我的解决方案:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
我的 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
谁能帮我弄清楚如何以零而不是一个开始每一行?
据我了解,很简单:
print("Whosebug")
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)
returns :
Whosebug
101
010
101
我正在处理相同类型的赋值,但是到目前为止我们只介绍了条件语句和 while 循环,遵循相同的逻辑,这是我的解决方案:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101