String hashing using Polynomial rolling hash function | Function to calculate the hash of a string ; P and M ; Loop to calculate the hash value by iterating over the elements of string ; Driver Code ; Given string
def polynomialRollingHash ( str ) : NEW_LINE INDENT p = 31 NEW_LINE m = 1e9 + 9 NEW_LINE power_of_p = 1 NEW_LINE hash_val = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT hash_val = ( ( hash_val + ( ord ( str [ i ] ) - ord ( ' a ' ) + 1 ) * power_of_p ) % m ) NEW_LINE power_of_p = ( power_of_p * p ) % m NEW_LINE DEDENT return int ( hash_val ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE print ( " Hash ▁ of ▁ ' { } ' ▁ = ▁ { } " . format ( str1 , polynomialRollingHash ( str1 ) ) ) NEW_LINE DEDENT