"""
Write a function, called tree, which draws a tree given the width of its base
(the number of characters on the bottom-most row of the triangle section),
using ASCII art (printing characters to the screen).
The tree consists of a trunk of 3 hashes (###) and
a triangular shape on the top made of stars (*).
The triangle is centred on the trunk, with a base of N characters.
Each layer reduces by 2 character until it reaches a top layer of 1 character.
So a base of 3 shrinks to 1. A base of 7 shrinks to 5, 3 and 1.
N should be an odd number!
Function inputs:
- N, the base of the tree, an odd integer higher than (or equal to) 3.
- The trunk character, # by default
- The leaf character, * by default
Output: The function prints the following for tree(7):
*
***
*****
*******
###
Solution written by Lauren J Gregoire
"""
def draw_layer(width,num_char,char):
""" draw a layer of the tree
with num_char centered against the width
inputs:
- width of layer
- num_char: the number of characters
- char: the character to use in the layer
"""
#calculate number of spaces needed around the tree
padding = (width - num_char) / 2
# print tree layer
print ' ' * padding + char * num_char
def tree(N,trunk_char='#',leaf_char='*'):
""" draw a tree of width N
inputs:
- N, odd integer greater or equal to 3
- trunk_char (optional)
- leaf_char (optional)
"""
if (N < 3) or (N % 2 == 0):
print 'ERROR: The tree width should be an odd number greater than 3!'
else:
## print tree leaves
# Grow number of leaves from 1 to N (width of tree
# by adding two leafs each row
for num_leafs in range(1,N+1,2):
draw_layer(N,num_leafs,leaf_char)
## print trunk of width 3
draw_layer(N,3,trunk_char)
tree(7)
tree(21,leaf_char='+', trunk_char=':')