Memoization in python
I’m writing a genetic algorithm, which is pretty time consuming. I was thinking - why not use memoization and save some time. It appears pretty easy to do and there’re several examples for copy-paste in the internet, but it appeared that’s it not as simple as i thought it would be.
I’m trying to memoize (i’ll use cache from now) objects of a certain class. The class has some double precision data members, which i want to allow to be a little different, for example abs(self.a - rhs.a) < 0.1. It’s easy, just define __eq__ method. Now, let’s put objects into a dictionary (for caching)… oops - there’s an exception thrown - they are unhashable now.
Fast search in google revealed i need to define __hash__ method which must return equal results for equal objects…. Now it becomes non trivial at all.
In c++ it’s easy since std::map (stl equivalent of python’s dictonary) is based on operator< (or on comparison functor with the same functionality), and in python dictionary is based on hash value, which is faster but not easy calculable in my problem.
Is there something like std::map ready? Currently the solution was to round floating points members and cache them. Any better solutions?
Technorati Tags:
python, memoization, optimization, programming

