Printing Simple Diamond Pattern in Python

后端 未结 15 2603
执笔经年
执笔经年 2020-12-19 23:14

I would like to print the following pattern in Python 3.5 (I\'m new to coding):

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
         


        
15条回答
  •  一个人的身影
    2020-12-19 23:37

    Here is a solution base on height equals to top to the middle, or half of the height. For example, height is entered as 4(7) or 5(9) below. This method will yield odd number actual height

    h = eval(input("please enter diamond's height:"))
    
    for i in range(h):
        print(" "*(h-i), "*"*(i*2+1))
    for i in range(h-2, -1, -1):
        print(" "*(h-i), "*"*(i*2+1))
    
    # please enter diamond's height:4
    #      *
    #     ***
    #    *****
    #   *******
    #    *****
    #     ***
    #      *
    #
    # 3, 2, 1, 0, 1, 2, 3  space
    # 1, 3, 5, 7, 5, 3, 1  star
    
    # please enter diamond's height:5
    #       *
    #      ***
    #     *****
    #    *******
    #   *********
    #    *******
    #     *****
    #      ***
    #       *
    #
    # 4, 3, 2, 1, 0, 1, 2, 3, 4  space
    # 1, 3, 5, 7, 9, 7, 5, 3, 1  star
    

    Here is another solution base on height equals to top to the bottom, or the actual total height. For example, height is entered as 7 or 9 below. When the user enters an even number for height, the diamond will be slightly slanted.

    h = eval(input("please enter diamond's height:"))
    
    for i in range(1, h, 2):
        print(" "*(h//2-i//2), "*"*i)
    for i in range(h, 0, -2):
        print(" "*(h//2-i//2), "*"*i)
    
    # please enter diamond's height:7
    #      *
    #     ***
    #    *****
    #   *******
    #    *****
    #     ***
    #      *
    #
    # 3, 2, 1, 0, 1, 2, 3  space
    # 1, 3, 5, 7, 5, 3, 1  star
    #
    # please enter diamond's height:9
    #       *
    #      ***
    #     *****
    #    *******
    #   *********
    #    *******
    #     *****
    #      ***
    #       *
    #
    # 4, 3, 2, 1, 0, 1, 2, 3, 4  space
    # 1, 3, 5, 7, 9, 7, 5, 3, 1  star
    

提交回复
热议问题