Hamming Distance

Raymond Hettinger python at rcn.com
Fri Jun 20 01:50:50 CEST 2008


On Jun 19, 4:27 pm, godavemon <davefow... at gmail.com> wrote:
> I need to calculate the Hamming Distance of two integers.  The hamming
> distance is the number of bits in two integers that don't match.  I
> thought there'd be a function in math or scipy but i haven't been able
> to find one.  This is my function but it seems like there should be a
> faster way.  I do this computation many times and speed up is
> important.

The simplest speed-up is to break the inputs into n-length blocks and
then look them up in an n-by-n table.

Also, re-write your function to use iteration instead of recursion
(the latter is *very* expensive in Python).

The fastest way is to write a C function or use Pyrex.


Raymond



More information about the Python-list mailing list