Skip to content
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

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions hashes/polynomial_hash.py
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.
Copy link
Contributor

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?


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):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: polynomial_hash. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file hashes/polynomial_hash.py, please provide doctest for the function polynomial_hash

Please provide type hint for the parameter: s

Please provide descriptive name for the parameter: s

Please provide type hint for the parameter: p

Please provide descriptive name for the parameter: p

Please provide type hint for the parameter: m

Please provide descriptive name for the parameter: m

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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please encapsulate all driver code in a __main__ block.