# find the harsh values for substrings of length k in S
def hashcal(S,k):
scale = 26 # a random constant value
modval = (1<<31) - 1 # to constrain the hash value range
pow_k = scale**(k-1)%modval # pow_k constrains for large k
N = len(S)
hashbuffer = [0]*(N-k+1) # save the hash values
# Variable to the hash
hashv = 0
# Finding hash of the first substring
for i in range(k) :
hashv = (hashv * scale + (ord(S[i]) - 97)) % modval # the shifted ascii values can be extracted in advance
hashbuffer[0] = hashv
# rolling hashtable
for i in range(k,N):
hashv = ((hashv - pow_k * (ord(S[i-k]) - 97)) * scale + (ord(S[i]) - 97)) % modval
hashbuffer[i-k+1]=hashv
return hashbuffer