In: Computer Science
Python question
Define a function called hash_string_weighted_folding(string_to_hash, modulus) that takes two parameters: a string variable string_to_hash and an integer called modulus. The function returns an integer that is the hash value of string_to_hash.
This hash function processes the string in blocks of 4 characters (the final block may be shorter depending on the length of string_to_hash) and multiplies each character’s ASCII value by a weight. The weight depends on the position of the character in the block of 4 characters: the ASCII value of the character in the first position is multiplied by 256 to the power of zero (i.e., by 1); the character in the second position has its ASCII value multiplied by 256 to the power of 1 (i.e., by 256); the third character has its ASCII value multiplied by 256 to the power of 2; and the fourth character in each block has its ASCII value multiplied by 256 to the power of 3. All of the resulting weighted values are summed and the function returns the result of this sum modulus the parameter modulus.
Note: You can use the inbuilt Python ord() function to return the ASCII value of a string character.
For example:
Test | Result |
---|---|
string_to_hash = "Kea" print(hash_string_weighted_folding(string_to_hash, 5519)) |
2959 |
string_to_hash = "Piwaiwaka" print(hash_string_weighted_folding(string_to_hash, 6089)) |
5997 |
string_to_hash = "Kaki" print(hash_string_weighted_folding(string_to_hash, 3797)) |
2339 |
Firstly the string should be divided into blocks of length 4 and stores these blocks into a list then iterate each block in the list and calculate the weighted sum.
Code:
def hash_string_weighted_folding(string_to_hash, modulus):
n=4 #each block length is 4
blocks=[] #stores all blocks
#if length of sting is a multiple of 4
if len(string_to_hash)%4==0:
for i in range(0, len(string_to_hash), n):
blocks.append(string_to_hash[i:i+n])
#length of a string is not a multiple of 4
else:
d=len(string_to_hash)%4
i=0
if len(string_to_hash)>4:
for i in range(0, len(string_to_hash)-d, n):
blocks.append(string_to_hash[i:i+n])
blocks.append(string_to_hash[i+n:])
else:
blocks.append(string_to_hash)
total=0
#calculate the sweighted sum of the chars
for k in blocks:
for m in range(len(k)):
total+=(ord(k[m])*256**m)
return total%modulus
#driver code
#to test the above function
string_to_hash = "Kea"
print(hash_string_weighted_folding(string_to_hash, 5519))
string_to_hash = "Piwaiwaka"
print(hash_string_weighted_folding(string_to_hash, 6089))
string_to_hash = "Kaki"
print(hash_string_weighted_folding(string_to_hash, 3797))
Output:
2959
5997
2339
Please refer to the screenshots below for correct indentations