Minor edit: performance optimization using xrange.
Adding patch to avoid division by zero error.