Created
April 19, 2025 18:11
-
-
Save JulianNorton/fd7f974aab5ac4b5eaa781d26bc7f0d8 to your computer and use it in GitHub Desktop.
model_A_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
import ctypes | |
def to_int32(value): | |
"""Casts a Python integer to a 32-bit signed integer.""" | |
return ctypes.c_int32(value).value | |
def string_hash_py(s): | |
""" | |
Python equivalent of the provided JavaScript stringHash function. | |
Args: | |
s: The input string. | |
Returns: | |
The calculated hash as a positive integer. | |
""" | |
hash_val = 0 # Use standard Python arbitrary-precision integer | |
for char in s: | |
char_code = ord(char) # Get Unicode code point, similar to JS charCodeAt | |
# --- Critical part: Simulate JavaScript's bitwise shift behavior --- | |
# 1. Convert the current hash_val to a 32-bit signed integer representation | |
# just for the shift operation, like JS does implicitly. | |
hash_val_int32 = to_int32(hash_val) | |
# 2. Perform the left shift on the 32-bit value. | |
# The result will automatically wrap around if it exceeds 32 bits, | |
# matching the JavaScript behavior for `(hash << 5)`. | |
shifted_hash = hash_val_int32 << 5 | |
# 3. Perform the subtraction and addition using standard Python integers. | |
# Crucially, use the *original* potentially large `hash_val` for the | |
# subtraction, as per the JS formula `(hash << 5) - hash + char`. | |
hash_val = shifted_hash - hash_val + char_code | |
# --- End of critical part --- | |
# Return the absolute value, like JS Math.abs() | |
return abs(hash_val) | |
# --- Test Case --- | |
input_string = "let's get it started" | |
result = string_hash_py(input_string) | |
print(f"Input string: '{input_string}'") | |
print(f"Python hash result: {result}") | |
# Verification | |
expected_result = 7644365391 | |
print(f"Expected result: {expected_result}") | |
print(f"Result matches expected: {result == expected_result}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment