我需要在Python中创建一个具有一定高度和长度的正方形。该代码应采用这两个参数并打印一个带有字母 O 和 I 的框,交替使用它们。它必须与 yes 行开头的字母交替。它应该看起来像这样
>>>square(5,5)
OIOIO
IOIOI
OIOIO
IOIOI
OIOIO
# Note how each row and each column alternate!
>>> square(5,10)
OIOIOIOIOI
IOIOIOIOIO
OIOIOIOIOI
IOIOIOIOIO
OIOIOIOIOI
>>> square(2,4)
OIOI
IOIO
到目前为止我已经有了这个,但老实说我不知道如何让它交替以及如何修改高度
def square(height, length):
a='square'
c=(height/2)
num=0
symbol='OI'
while a=='square' and int(num)<int(c):
num+=1
print(symbol*int(c))
建议在另一个for循环中使用一个for循环。
最佳答案
您可以使用生成器表达式、str.join
和 itertools.cycle()
。
示例:
from __future__ import print_function
from itertools import cycle
try:
range = xrange # Python 2/3 compatibility
except NameError:
pass
def square(height, width, symbols="OI"):
it = cycle(symbols)
return "\n".join("".join(next(it) for _ in range(width)) for _ in range(height))
输出:
>>> print(square(2, 4))
OIOI
OIOI
>>> print(square(5, 5))
OIOIO
IOIOI
OIOIO
IOIOI
OIOIO
Using
itertools.cycle()
also ensures that the pattern also changes per row.
关于python - 创建一个正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721436/