[SciPy-User] Smart Hashing of Integer Numbers

Robin robince at gmail.com
Thu Sep 24 08:41:51 EDT 2009


On Thu, Sep 24, 2009 at 1:17 PM, Lorenzo Isella
<lorenzo.isella at gmail.com> wrote:
> Dear All,
> This is my problem: I have a couple of integer numbers (which are
> entries of a numpy array) and I would like to combine them unambiguously
> into a single (possibly short) integer number.
> There are two requirements
> (1) then function f(A,B)=C must be injective
> (2) it would be very pleasant to be able to decompose unambiguously C
> into A and B

If you treat your pair of numbers A,B as a length 2 word with base m =
maximum possible value of A or B, then you can get what you want by
converting to decimal and back.

eg C = A^m + B

Here are some (probably slightly iffy) functions I have to this (be
careful with the dimensions of what you pass in):

def base2dec(x,b):
    """Convert a numerical vector to its decimal value in a given base b."""
    xs = x.shape
    z = b**np.arange((xs[1]-1),-0.5,-1)
    y = np.asarray(np.dot(x, z))
    return y

def dec2base(x, b, digits):
    """Convert decimal value to a row of (digits) values representing it in a
    given base b."""
    xs = x.shape
    if xs[1] != 1:
        raise ValueError, "Input x must be a column vector!"
    power = np.ones((xs[0],1)) * (b ** np.c_[digits-1:-0.5:-1,].T)
    x = np.tile(x,(1,digits))
    y = np.floor( np.remainder(x, b*power) / power )
    return y

Cheers

Robin



More information about the SciPy-User mailing list