Printing Simple Diamond Pattern in Python

后端 未结 15 2622
执笔经年
执笔经年 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:32

    simple way ...

    n= 11 #input is even number 1,3,5,...
    a = 1
    b = 1
    for a in range(n+1):
        if a%2 != 0:
            val = (n - a) // 2
            print (" "*val + "*"*(a) + " "*val ,end = "\n")
    for b in range(n-1,0,-1):
        if b%2 != 0:
            val2 = (n-b)//2
            print (" "*val2 + "*"*(b) + " "*val2 ,end = "\n")
    

    Output:

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

    Or using reverse method, first one is diamond, second one is series of diamond

    import copy
    n = 10       #input: size of diamon
    raw  = []
    lst = []
    re_lst = []
    
    for a in range(n+1):
        if a%2 != 0:
            val = (n - a) // 2
            raw = ''.join(" "*val + "*"*(a) + " "*val)
            lst.append(raw)
            re_lst = copy.deepcopy(lst)
    lst.reverse()
    #print diamond
    for i in re_lst:
        print(i)
    for i in lst:
        print(i)
    print("\n")
    #print series of diamond
    for i in re_lst:
        print(i)
        for i in lst:
            print(i)
    

提交回复
热议问题