Skip to main content

11.12) Challenge 34 (Hard) - Draw A Tree


Write a function, called ‘Tree’, that 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 characters 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 then 1. N should be an odd number.
Function inputs:

  • N, the base of the tree, an odd integer higher than (or equal to) 3. (Print an error if N does not fit the criteria).
  • The trunk character, # by default
  • The leaf character, * by default

Output: The function prints the following for tree(7):

   *
  ***
 *****
*******
  ###

Advanced: If you can identify operations that you wrote more than once in the code, write a separate function for them and call them within your function tree.
Hint: Divide the tasks that the program will do and start writing the core tasks first. Try printing a half tree first and then worry about how to centre it on the trunk.
Solution: tree_generation_function_solution.py