# Numbers of alphabet which we call basealphabet_size = 256# Modulus to hash a stringmodulus = 1000003def rabin_karp(pattern, text):"""The Rabin-Karp Algorithm for finding a pattern within a piece of textwith complexity O(nm), most efficient when it is used with multiple patternsas it is able to check if any of a set of patterns match a section of text in o(1)given the precomputed hashes.This will be the simple version which only assumes one pattern is being searchedfor but it's not hard to modify1) Calculate pattern hash2) Step through the text one character at a time passing a window with the samelength as the patterncalculating the hash of the text within the window compare it with the hashof the pattern. Only testing equality if the hashes match"""p_len = len(pattern)t_len = len(text)if p_len > t_len:return Falsep_hash = 0text_hash = 0modulus_power = 1# Calculating the hash of pattern and substring of textfor i in range(p_len):p_hash = (ord(pattern[i]) + p_hash * alphabet_size) % modulustext_hash = (ord(text[i]) + text_hash * alphabet_size) % modulusif i == p_len - 1:continuemodulus_power = (modulus_power * alphabet_size) % modulusfor i in range(0, t_len - p_len + 1):if text_hash == p_hash and text[i : i + p_len] == pattern:return Trueif i == t_len - p_len:continue# Calculate the https://en.wikipedia.org/wiki/Rolling_hashtext_hash = ((text_hash - ord(text[i]) * modulus_power) * alphabet_size+ ord(text[i + p_len])) % modulusreturn Falsedef test_rabin_karp():""">>> test_rabin_karp()Success."""# Test 1)pattern = "abc1abc12"text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"text2 = "alskfjaldsk23adsfabcabc"assert rabin_karp(pattern, text1) and not rabin_karp(pattern, text2)# Test 2)pattern = "ABABX"text = "ABABZABABYABABX"assert rabin_karp(pattern, text)# Test 3)pattern = "AAAB"text = "ABAAAAAB"assert rabin_karp(pattern, text)# Test 4)pattern = "abcdabcy"text = "abcxabcdabxabcdabcdabcy"assert rabin_karp(pattern, text)# Test 5)pattern = "Lü"text = "Lüsai"assert rabin_karp(pattern, text)pattern = "Lue"assert not rabin_karp(pattern, text)print("Success.")if __name__ == "__main__":test_rabin_karp()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。