-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create polynomial_hash.py #9160
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
""" | ||
Calculate the hash of a string using a polynomial rolling hash function. | ||
|
||
Args: | ||
s (str): The input string to be hashed. | ||
p (int): A prime number to serve as the base for the polynomial hash (default is 31). | ||
m (int): A large prime number to prevent integer overflow (default is 10^9 + 9). | ||
|
||
Returns: int: The computed hash value. | ||
Wikipedia :: https://en.wikipedia.org/wiki/Hash_function | ||
""" | ||
|
||
|
||
def polynomial_hash(s, p=31, m=10**9 + 9): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide return type hint for the function: As there is no test file in this pull request nor any test function or class in the file Please provide type hint for the parameter: Please provide descriptive name for the parameter: Please provide type hint for the parameter: Please provide descriptive name for the parameter: Please provide type hint for the parameter: Please provide descriptive name for the parameter: |
||
hash_value = 0 | ||
p_pow = 1 | ||
for char in s: | ||
char_value = ord(char) - ord("a") + 1 # Convert character to a numerical value | ||
hash_value = (hash_value + char_value * p_pow) % m | ||
p_pow = (p_pow * p) % m | ||
return hash_value | ||
|
||
|
||
print(polynomial_hash("PythonLanguage")) | ||
# Output: 877483825 | ||
Comment on lines
+24
to
+25
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please encapsulate all driver code in a |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this is a polynomial rolling hash, then why not name the file and function
polynomial_rolling_hash
?