Skip to content

Instantly share code, notes, and snippets.

@Seniru
Created May 28, 2025 08:58
Show Gist options
  • Select an option

  • Save Seniru/154b45a371d710a72aeac0f24e9ee889 to your computer and use it in GitHub Desktop.

Select an option

Save Seniru/154b45a371d710a72aeac0f24e9ee889 to your computer and use it in GitHub Desktop.
# 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