JaAnTr
JaAnTr

Reputation: 906

Making a tree shape.

I'm trying to print something that looks like this:

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

with the user inputting the width of the thickest part of the head and the width of the stem.

So far I have managed to get the head to print using this code:

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")

But I'm completely stuck on how to do the stem of the tree.

Upvotes: 0

Views: 938

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

Something like this:

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)
  *  
 *** 
*****
  *  
  *  
  *  

Update:

To keep the width of stem in proportion to width of 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)
      *       
     ***      
    *****     
   *******    
  *********   
 ***********  
************* 
   *******    
   *******    
   *******    
   *******    

Upvotes: 4

Related Questions