python / refactoring

The Triangle Project, initial and recursive

(follows from ‘Refactoring, the triangle project overview)

Through this series of blogs, I want to record my pythonic adventures and refactor my existing code to reflect my new skills. In the Triangle Project, I must develop some code to print the outline of a triangle. The triangle must be able to be printed either upright, or upside down.

Triangle v1.0:


Hacking it up:   above is my first attempt to hack this up. It is quick and dirty, but does the job. Below, you will see my first attempt to refactor it using recursion.

Triangle v2.0


Improvement from the initial hack (v1.0) to the recursive solution (v2.0):

To  be honest, using a recursive function does not actually make any difference to this program. It is not any more elegant or abstracted than a simple for loop could achieve. However, the script is about 20% shorter.

The real improvements in v2.0 include:

  • docstring
  • removal of redundant ‘regular’ flag in function arguments
  • improved logic for calculating the inner and outer padding
  • use of string formatting to simplify code (this is far more elegant that string concatenation IMHO)

So while recursion does not lend much to this script, that is not the point! I have implemented something new, acquired during my pythonic adventures, and I think that is pretty awesome 🙂


2 thoughts on “The Triangle Project, initial and recursive

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s