Created
April 19, 2025 18:14
-
-
Save JulianNorton/4ebb3ca0d8b9bdc528aecba531db1250 to your computer and use it in GitHub Desktop.
model_C_answer.py
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
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