Predict the output
What does this print?
text, m, base, mod = "abcab", 2, 31, 1_000_003
def h(s: str) -> int:
v = 0
for ch in s:
v = (v * base + ord(ch)) % mod
return v
windows = [h(text[i:i + m]) for i in range(len(text) - m + 1)]
print(windows[0] == windows[3], windows[0] == windows[1])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True False
Right: windows 0 and 3 are both 'ab', and 'ab' differs from 'bc'.
Equal windows always hash equally, but the reverse is only likely, which is why a match is confirmed by comparing characters.
Why not the others?
- B False False. Equal strings always have equal hashes.
- C True True. Different strings usually have different hashes.