Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JulianNorton/4ebb3ca0d8b9bdc528aecba531db1250 to your computer and use it in GitHub Desktop.
Save JulianNorton/4ebb3ca0d8b9bdc528aecba531db1250 to your computer and use it in GitHub Desktop.
model_C_answer.py
def string_hash(s):
hash_val = 0
for char in s:
char_code = ord(char)
hash_val = ((hash_val << 5) - hash_val) + char_code
# In JavaScript, bitwise operations work on 32-bit integers
# so we need to simulate the same behavior in Python
hash_val = hash_val & 0xFFFFFFFF # Keep only the lower 32 bits
# If the value is negative (highest bit is 1), convert to positive
if hash_val & 0x80000000:
hash_val = hash_val & 0x7FFFFFFF # Clear the sign bit
return hash_val
# Test
result = string_hash("let's get it started")
print(result) # Should output 7644365391
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment