创造一个广场

时间:2015-06-09 01:03:39

标签: python string for-loop

我需要在python中创建一个具有一定高度和长度的正方形。代码应该采用这两个参数并打印一个带有字母O和I的框,交替使用它们。它必须与所谓的行开始交替。它应该看起来像这样

>>>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循环。

3 个答案:

答案 0 :(得分:1)

您可以使用生成器表达式str.joinitertools.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
  

使用itertools.cycle()也可确保模式也发生变化   每行。

答案 1 :(得分:0)

您可以使用函数获取每个位置的字符,并使用.join形成一行

def charAt(x, y):
    return "O" if (x+y)%2==0 else "I"

def square(x_size, y_size):
    for x in range(x_size):
        print "".join([charAt(x, y) for y in range(y_size)])

答案 2 :(得分:0)

你可以试试这个当然不是最好的方法,但是直观的。阅读评论:

def square(height, width):
    symbols = "OI"  ## The characters to use.
    result = ""     ## Where we will collect each row.

    for row in range(height):
        current_row = ""
        for column in range(width):
            ## This line is to alternate between I's and O's
            ## using the parity of the current column:
            symbol_to_use = symbols[column%2]

            current_row += symbol_to_use
        result += current_row + "\n"

    ## The [:-1] bit is to remove the last "\n" (newline):
    return result[:-1]