From 566fa0eaa254270976eb27fc051681e6d9a24bf7 Mon Sep 17 00:00:00 2001 From: Prashuu <97186762+prasad-chavan1@users.noreply.github.com> Date: Sun, 1 Oct 2023 07:52:46 +0530 Subject: [PATCH 1/2] Create polynomial_hash.py --- hashes/polynomial_hash.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 hashes/polynomial_hash.py diff --git a/hashes/polynomial_hash.py b/hashes/polynomial_hash.py new file mode 100644 index 000000000000..677c9b9d686f --- /dev/null +++ b/hashes/polynomial_hash.py @@ -0,0 +1,22 @@ +""" +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): + 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 From 6a57de738b1dc18fbefab7261b9a39e329b08009 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 1 Oct 2023 02:24:57 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- hashes/polynomial_hash.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/hashes/polynomial_hash.py b/hashes/polynomial_hash.py index 677c9b9d686f..be5c61f2b59a 100644 --- a/hashes/polynomial_hash.py +++ b/hashes/polynomial_hash.py @@ -9,14 +9,17 @@ Returns: int: The computed hash value. Wikipedia :: https://en.wikipedia.org/wiki/Hash_function """ + + def polynomial_hash(s, p=31, m=10**9 + 9): hash_value = 0 p_pow = 1 for char in s: - char_value = ord(char) - ord('a') + 1 # Convert character to a numerical value + 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')) + +print(polynomial_hash("PythonLanguage")) # Output: 877483825