如何创建散列函数,该函数允许我在Python中为长度为N的数组索引指定特定字符串的情况下获得索引?
假设您创建了一个数组,其中包含N个项目,最好是无:例如:self.data = [None] * N, self.memory = N
def _hash(self, key):
hashed_value = 0
bucket_length = self.memory # refers to the bucket size Ex: for [[key, value, none], [key, value, [key, value, none]], None] it is 3
string_length = len(key)
i = 0
while i < string_length:
hashed_value += (ord(key[i]) * i) // bucket_length
if hashed_value > bucket_length-1:
hashed_value %= bucket_length-1
i += 1
return hashed_value # returns an integer in the range of 0 to bucket_length-1, inclusive for hashing