Functional Python Programming

(Wang) #1

Optimizations and Improvements


"""


if n == 0: return 1


else: return n*fact(n-1)


We added two edge cases: the explicit base case and the first item beyond the base
case. We also added another item that would involve multiple iterations. This allows
us to tweak the code with confidence.


When we have a more complex combination of functions, we might need to execute
commands like this:


test_example="""





binom= Binomial()








binom(52,5)





2598960


"""


test = {


"test_example": test_example,


}


The test variable is used by the doctest.testmod() function. All of the
values in the dictionary associated with the test variable are examined for the
doctest strings. This is a handy way to test features that come from compositions
of functions. This is also called integration testing, since it tests the integration of
multiple software components.


Having working code with a set of tests gives us the confidence to make optimizations.
We can easily confirm the correctness of the optimization. Here's a popular quote that
is used to describe optimization:


"Making a wrong program worse is no sin."

-Jon Bentley

This appeared in the Bumper Sticker Computer Science chapter of More Programming
Pearls, published by Addison-Wesley, Inc. What's important here is that we should
only optimize code that's actually correct.

Free download pdf