Skip to content

Commit

Permalink
Added W10 materials
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanSol committed Dec 9, 2024
1 parent 88b7141 commit a778c4f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
| 07 | DFS & BFS | [Slides][Slides_W07] | [Test][WarmUp_test_W07] | [Contest][ContestID_W07] | 25.11.2024 19:00 UTC+3 |
| 08 | Shortest paths | [Slides][Slides_W08] | [Test][WarmUp_test_W08] | [Contest][ContestID_W08] | 02.12.2024 19:00 UTC+3 |
| 09 | RSQ & RMQ | [Slides][Slides_W09] | [Test][WarmUp_test_W09] | [Contest][ContestID_W09] | 09.12.2024 19:00 UTC+3 |
| 10 | Hashing | [Slides][Slides_W10] | [Test][WarmUp_test_W10] | [Contest][ContestID_W10] | 16.12.2024 19:00 UTC+3 |
<!---
| 10 | Hashing | [Slides][Slides_W10] | [Test][WarmUp_test_W10] | [Contest][ContestID_W10] | ??.12.2024 19:00 UTC+3 |
| 11 | Binary Search Tree | [Slides][Slides_W11] | None | None | None |
--->

Expand Down
Binary file added week10_hashing/MSAI.2024.Algo.W10.slides.pdf
Binary file not shown.
34 changes: 34 additions & 0 deletions week10_hashing/rabin_karp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from random import randint


def c_to_i(ch):
return ord(ch) - ord('a') + 1


p = 10**9 + 7
a = randint(c_to_i('z') + 1, p - 1)


def find_substrings_rabin_karp(s, t):
h = [0] * (len(s) + 1)
a_pow = [1] * (len(s) + 1)
for i in range(len(s)):
h[i + 1] = (h[i] + c_to_i(s[i]) * a_pow[i]) % p
a_pow[i + 1] = (a_pow[i] * a) % p

h_t = 0
for i in range(len(t)):
h_t = (h_t + c_to_i(t[i]) * a_pow[i]) % p

substrings = []
for i in range(len(s) - len(t) + 1):
if (h_t * a_pow[i]) % p == (h[i + len(t)] - h[i]) % p:
if all([s[i + j] == t[j] for j in range(len(t))]):
substrings.append(i)
return substrings


if __name__ == '__main__':
s = input().strip()
t = input().strip()
print(' '.join(map(str, find_substrings_rabin_karp(s, t))))

0 comments on commit a778c4f

Please sign in to comment.