Last active
August 4, 2018 09:51
-
-
Save varunvora/bba0c9e217968dbbfcaa13b2a56ed08c to your computer and use it in GitHub Desktop.
Python 2's hash() function in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Implementation of hash() differs in Python 2 and Python 3 | |
To use Python 2's hash() in Python 3, use the following snippet. | |
Note that this snippet computes the expected hash only of input of type str | |
Source: https://www.laurentluce.com/posts/python-dictionary-implementation/ | |
""" | |
import numpy as np | |
def str_hash(string): | |
x = np.array([ord(string[0]) << 7], dtype=int) | |
if not string: | |
return 0 # empty | |
for char in string: | |
x[0] = (1000003 * x[0]) ^ ord(char) | |
x[0] = x[0] ^ len(string) | |
return x[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment