如何打印半角星号方块?

时间:2019-03-19 17:38:35

标签: python design-patterns

我可以得到空心的正方形,但似乎无法弄清楚如何填充正方形的右半部分。这就是我所拥有的...

def star():
    """ Display a star without the normal new line """
    print('*', end='')
def space():
    """ Display a space without the normal new line """
    print(' ', end='')
def newline():
    """ Display a new line """
    print()

def halfAndHalf(size):
    """ Display a square that is half filled 
        - This example has size = 6
    ******  
    *  ##*
    *  ##*
    *  ##*
    *  ##*
    ******    
    """
    print('Half and half square of size', size)
    for i in range(size):
        star()
    newline()
    for i in range(size - 2):
        star()
        for j in range(size - 2):
            space()
        star()
        newline()
    for i in range(size):
        star()
    newline()

2 个答案:

答案 0 :(得分:0)

添加显式检查:

def star(): print('*', end = '')
def newline(): print()
def space(): print(' ', end = '')
def sharp(): print('#', end = '')

def halfAndHalf(size):
    print('Half and half square of size', size)
    for i in range(size):
        star()

    newline()
    sz = size - 2;

    for i in range(sz):
        star()
        for j in range(sz):
            space() if (j < sz / 2) else sharp(); # <- check here

        star()
        newline()

    for i in range(size):
        star()

    newline()

def main():
  halfAndHalf(20);

if (__name__ == '__main__'):
  main();

输出:

Half and half square of size 20
********************
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
*         #########*
********************

如果您不熟悉space() if (j < sz / 2) else sharp()三元运算符,则可以使用简单的if或引用Python documentations

答案 1 :(得分:0)

您可以通过将总宽度除以边框除以2来计算左侧空白区域的宽度,并通过从边框除以边框的总宽度中减去该宽度来计算右侧的散列宽度(我已经替换了您的辅助函数以提高可重复性):

def halfAndHalf(size):
    print('Half and half square of size', size)
    for i in range(size):
        print('*', end='')
    print('\n', end='')
    for i in range(size - 2):
        padding_size = size // 2 - 1
        print('*', end='')
        for j in range(padding_size):
            print(' ', end='')
        for j in range(size - 2 - padding_size):
            print('#', end='')
        print('*', end='')
        print('\n', end='')
    for i in range(size):
        print('*', end='')
    print('\n', end='')

请注意,您可以对字符串使用repeat运算符,而不必重复循环来重复打印字符,因此下面的代码就足够了,并且更具可读性:

def halfAndHalf(size):
    print('Half and half square of size', size)
    print('*' * size)
    padding_size = size // 2 - 1
    for i in range(size - 2):
        print('*' + ' ' * padding_size + '#' * (size - 2 - padding_size) + '*')
    print('*' * size)