Optimize a python bottleneck