Performance enhancements 

First commit: memoization (caching values) to use a dictionary lookup instead of recalculating values. Should be constant time no matter the size of the dictionary.
Second commit: imports into local namespace; attribute access is expensive, especially for inner loops and loops that are getting called a lot