Created
May 28, 2025 08:58
-
-
Save Seniru/154b45a371d710a72aeac0f24e9ee889 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Increase the divisor to reduce the number of spurious hits | |
| DIVISOR = 13 | |
| # this is a ultra simplified version of rabin karp method to demonstrate the logic behind it. | |
| # this method only works for integer strings, has to be modified a little to support strings | |
| def rabin_karp_string_matcher(string, pattern): | |
| modulo = sum(pattern) % DIVISOR | |
| string_len = len(string) | |
| pattern_len = len(pattern) | |
| for i in range(string_len - pattern_len + 1): | |
| sub_modulo = sum(string[i:i+pattern_len]) % DIVISOR | |
| if sub_modulo == modulo: # hit! | |
| # check the hit further to identify valid and spurious hits | |
| if string[i:i+pattern_len] == pattern: | |
| return i | |
| return -1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment