簡體   English   中英

制作樹形。

[英]Making a tree shape.

我正在嘗試打印如下內容:

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

用戶輸入頭部最厚部分的寬度和桿的寬度。

到目前為止,我已經設法使用以下代碼進行打印:

def head(size):
    n=1
    while n < size+1:
        astri = n * "*"
        print '{:^50}'.format(astri)
        n += 2

 print head(x)

x = input("Please enter an odd integer for the head")

但是我完全堅持如何做樹的莖。

像這樣:

def tree(head, stem):
    #for head
    for i in xrange(1, head+1, 2):
        print '{:^{}}'.format('*'*i, head)
    #for trunk
    for _ in xrange(3):
        print '{:^{}}'.format('*'*stem, head)
...         
>>> tree(10, 3)
    *     
   ***    
  *****   
 *******  
********* 
   ***    
   ***    
   ***    
>>> tree(5, 1)
  *  
 *** 
*****
  *  
  *  
  *  

更新:

使stem寬度與head寬度成比例:

def tree(head, stem):
    for i in xrange(1, head+1, 2):
        print ('*'*i).center(head)
    x = (head/2) if (head/2)%2 else (head/2)-1
    for _ in xrange(stem):
        print ('*'*x).center(head)

>>> tree(12, 2)
     *      
    ***     
   *****    
  *******   
 *********  
*********** 
   *****    
   *****    
>>> tree(14, 4)
      *       
     ***      
    *****     
   *******    
  *********   
 ***********  
************* 
   *******    
   *******    
   *******    
   *******    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM