-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_substring.py
More file actions
executable file
·59 lines (41 loc) · 1.39 KB
/
hash_substring.py
File metadata and controls
executable file
·59 lines (41 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Find Pattern In Text
# Rabin-Karp's algorithm implementation.
# Author: jerrybelmonte
from random import randint
def read_input():
return input().rstrip(), input().rstrip()
def print_occurrences(output):
print(' '.join(map(str, output)))
def poly_hash(s, prime, number):
hash_value = 0
for i in range(len(s) - 1, -1, -1):
hash_value = (hash_value*number + ord(s[i])) % prime
return hash_value
def precomputed_hashes(text, size, prime, number):
n = len(text)
substr = text[n - size:n]
hashes = [None] * (n - size + 1)
value = 1
for _ in range(1, size + 1):
value = (value * number) % prime
hashes[n - size] = poly_hash(substr, prime, number)
for i in range(n - size - 1, -1, -1):
hashes[i] = (
number*hashes[i + 1] + ord(text[i]) - value*ord(text[i + size])
) % prime
return hashes
def rabin_karp(pattern, text):
size = len(pattern)
prime = 1000000007
rand_num = randint(1, prime - 1)
poly_hash_val = poly_hash(pattern, prime, rand_num)
computed_hash = precomputed_hashes(text, size, prime, rand_num)
result = []
for i in range(len(text) - size + 1):
if poly_hash_val != computed_hash[i]:
continue
if text[i:i + size] == pattern:
result.append(i)
return result
if __name__ == '__main__':
print_occurrences(rabin_karp(*read_input()))