python - 在 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
有人可以帮我弄清楚如何以零而不是一开始每隔一行吗?
解决方案
据我了解,这很简单:
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
推荐阅读
- python-3.x - 如何在 matplotlib ax.imshow() 中使用“extent”而不更改覆盖的 ax.text() 句柄的位置?
- python - 更改重复值索引
- actionscript-3 - 这是我的 AS3 AIR 桌面应用程序中的内存泄漏,还是我不应该担心?
- neo4j - Neo4j:启动 Neo4j 太慢并且失败
- python - 有没有办法逐步计算列的数据框的平均值?
- python - 我想在python中使用excel的v-lookup
- vulkan - 不取消映射 vulkan 内存
- csv - 读取 CSV 文件以散列会给出不正确的结果
- ios - 从不同的块并发访问相同的变量 - Swift
- angular - Angular 在自定义管道中添加标记