Skip to content

Instantly share code, notes, and snippets.

@apg
Created August 11, 2010 15:19
Show Gist options
  • Save apg/519140 to your computer and use it in GitHub Desktop.
Save apg/519140 to your computer and use it in GitHub Desktop.
def hashCode(s):
"""Computes the java `hashCode()` of a str
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], where n is len(s)
"""
TWO_31 = 2147483648
TWO_32 = 4294967296
l = len(s)
code = 0
for i, c in enumerate(s):
code += ord(c) * (31**(l-1-i))
# convert to 32 bit integer
return (code + TWO_31) % TWO_32 - TWO_31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment