Making diamond ASCII art with Python

前端 未结 2 489
自闭症患者
自闭症患者 2021-01-13 12:44

I\'m having trouble making this diamond. Whenever I make chars equal to an even length, it turns out fine. However, when it is odd, only the bottom portion of the diamond ge

2条回答
  •  独厮守ぢ
    2021-01-13 13:07

    Strategy: since the top half of the diamond is rendered correctly by the existing program, generate the top half and then generate the bottom half by reversing the lines from the top half. build_diamond returns a list containing the strings for the top half. print('\n'.join(string_list)) prints the top half. bottom_of_diamond_string_list = list(reversed(string_list))[1:] reverses the strings from the top half and removes the middle string with [1:] to get the strings for the bottom half. print('\n'.join(bottom_of_diamond_string_list)) prints the bottom half. Tested and works for 5 and 6 (even and odd) chars length. A lot more code clean up can be done, if desired.

    chars = 'ABCDEF'
    length = len(chars)
    
    def build_diamond(length):
        dots = (length*2 - 1)*2 - 1
        string = ''
        string_list = []
        for i in range(length):
            string1 = ''
            string += chars[i]
            length1 = len(string)
            for j in range(0, length1):
                if j % 2 != 0:
                    string1 += chars[length -1 - j].center(3, '.')
                else:
                    string1 += chars[length - 1 - j]
            for k in range(i - 1, -1, -1):
                if k % 2 != 0:
                    string1 += chars[length - 1 - k].center(3, '.')
                else:
                    string1 += chars[length - 1 - k]
            string1 = string1.center(dots, '.')
            string_list.append(string1)
        return string_list
    
    if __name__ == '__main__':
        string_list = build_diamond(length)
        print('\n'.join(string_list))
        bottom_of_diamond_string_list = list(reversed(string_list))[1:]
        print('\n'.join(bottom_of_diamond_string_list))
    

提交回复
热议问题