Simple hash function for characters

Simple Hash Function Implementation

The requirements for this hash function are

1. Values for each alpabet should remain the same for all conversions
2. abc should not be equal to cba or bac
3. Consider only lower case characters (not to complicate things)

def hashString(input):
    prim = 2049982463
    ret = 0
    for i in input:
        i = ord(i)
        print ("ret(%d) = (%d)*8 + (%d)" % (ret, ret, i))
        ret = ret*8 + i
    if ret > 0:
        return ret % prim
    else:
        return -ret % prim


def main():
    print hashString('and')
    print hashString('dan')
    print hashString('abc')
    print hashString('cba')


if __name__ == '__main__':
    main()

Output for the above source code would be as below

ret(0) = (0)*8 + (97)
ret(97) = (97)*8 + (110)
ret(886) = (886)*8 + (100)
7188
ret(0) = (0)*8 + (100)
ret(100) = (100)*8 + (97)
ret(897) = (897)*8 + (110)
7286
ret(0) = (0)*8 + (97)
ret(97) = (97)*8 + (98)
ret(874) = (874)*8 + (99)
7091
ret(0) = (0)*8 + (99)
ret(99) = (99)*8 + (98)
ret(890) = (890)*8 + (97)
7217

Another implementation for a simple hash function. I like better than the one above.


def simple_hash_function(hash):
    ret = 0
    for i in hash:
        print ("ret=(%d) = 31 * ret=(%d) + ord(i)=(%d)" % (ret, ret, ord(i)))
        ret = 31*ret + ord(i)
    return ret


def main():

    print simple_hash_function("abc")
    print simple_hash_function("cba")
    print simple_hash_function("bac")
    print simple_hash_function("dan")
    print simple_hash_function("and")


if __name__ == '__main__':
    main()

Output of the above code


ret=(0) = 31 * ret=(0) + ord(i)=(97)
ret=(97) = 31 * ret=(97) + ord(i)=(98)
ret=(3105) = 31 * ret=(3105) + ord(i)=(99)
96354
ret=(0) = 31 * ret=(0) + ord(i)=(99)
ret=(99) = 31 * ret=(99) + ord(i)=(98)
ret=(3167) = 31 * ret=(3167) + ord(i)=(97)
98274
ret=(0) = 31 * ret=(0) + ord(i)=(98)
ret=(98) = 31 * ret=(98) + ord(i)=(97)
ret=(3135) = 31 * ret=(3135) + ord(i)=(99)
97284
ret=(0) = 31 * ret=(0) + ord(i)=(100)
ret=(100) = 31 * ret=(100) + ord(i)=(97)
ret=(3197) = 31 * ret=(3197) + ord(i)=(110)
99217
ret=(0) = 31 * ret=(0) + ord(i)=(97)
ret=(97) = 31 * ret=(97) + ord(i)=(110)
ret=(3117) = 31 * ret=(3117) + ord(i)=(100)
96727

Leave a comment