|
| 1 | +#String matching by Rabin-Kap algorithm |
| 2 | + |
| 3 | +def generate_hash(text, pattern): |
| 4 | + ord_text = [ord(i) for i in text] |
| 5 | + ord_pattern = [ord(i) for i in pattern] |
| 6 | + len_text = len(text) |
| 7 | + len_pattern = len(pattern) |
| 8 | + len_hash_array = len_text - len_pattern + 1 |
| 9 | + hash_text = [0]*(len_hash_array) |
| 10 | + hash_pattern = sum(ord_pattern) |
| 11 | + |
| 12 | + for i in range(0, len_hash_array): |
| 13 | + if i == 0: |
| 14 | + hash_text[i] = sum(ord_text[:len_pattern]) |
| 15 | + else: |
| 16 | + hash_text[i] = ((hash_text[i - 1] - ord_text[i - 1]) + ord_text[i+len_pattern-1]) |
| 17 | + return [hash_text, hash_pattern] |
| 18 | + |
| 19 | + |
| 20 | +def Rabin_Karp_Matcher(text, pattern): |
| 21 | + text = str(text) |
| 22 | + pattern = str(pattern) |
| 23 | + hash_text, hash_pattern = generate_hash(text, pattern) |
| 24 | + len_text = len(text) |
| 25 | + len_pattern = len(pattern) |
| 26 | + flag = False |
| 27 | + for i in range(len(hash_text)): |
| 28 | + if hash_text[i] == hash_pattern: |
| 29 | + count = 0 |
| 30 | + for j in range(len_pattern): |
| 31 | + if pattern[j] == text[i + j]: |
| 32 | + count+=1 |
| 33 | + else: |
| 34 | + break |
| 35 | + if count == len_pattern: |
| 36 | + flag = True |
| 37 | + print("\nPattern occurs at index ", i) |
| 38 | + if not flag: |
| 39 | + print("Pattern is not at all present in the text") |
| 40 | + |
| 41 | + |
| 42 | +#Output of Rabin-Karp |
| 43 | +Rabin_Karp_Matcher("101110000011010010101101","1011") |
| 44 | +Rabin_Karp_Matcher("ABBACCADABBACCEDF","ACCE") |
0 commit comments