Created
April 19, 2025 18:12
-
-
Save JulianNorton/7a66bf221255e149752cdae1e323b2e8 to your computer and use it in GitHub Desktop.
model_B_answer.txt
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
Python’s integers never overflow, while the bit‑wise operators in JavaScript work on 32‑bit signed integers and silently wrap around. | |
To obtain exactly the same result we therefore have to force the intermediate | |
value (hash << 5) to overflow the way it does in JavaScript. | |
A handy way to do that in Python is to cast the value to a 32‑bit signed | |
integer each time we perform the shift. | |
import ctypes # gives us a 32‑bit signed C‑int wrapper | |
def string_hash(s: str) -> int: | |
hash_val = 0 | |
for ch in s: | |
# emulate JS overflow: (hash << 5) in signed 32‑bit arithmetic | |
hash_val = ctypes.c_int32(hash_val << 5).value - hash_val + ord(ch) | |
return abs(hash_val) | |
# ------------------------------------------------- | |
# test | |
print(string_hash("let's get it started")) # 7644365391 | |
Running the code prints | |
7644365391 | |
exactly like the original JavaScript function. | |
(The ctypes.c_int32(...).value call truncates the shifted value to 32 bits | |
and interprets it as a signed integer, reproducing JavaScript’s behaviour; | |
everything else is plain Python.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment