修改线性/二次散列,以便实现双重散列

时间:2017-05-27 11:36:46

标签: python hash

在完成线性和二次哈希问题后,我遇到了与双哈希相关的问题。

线性:

class BasicHashTable:
def __init__(self,size=7):
    self.size = size
    self.slots = [None] * self.size

def hash_function(self, key):
    return key%len(self.slots)

def rehash(self, old_pos):
    return (old_pos + 1) % self.size

def put(self, key):
    hash_value = key%len(self.slots)    
    probe_seq = []     
    insert_pos = hash_value     
    probe_seq += [insert_pos]     
    probes = 1     
    while(self.slots[insert_pos] != None):         
        probes += 1         
        insert_pos=(insert_pos+1)%len(self.slots)         
        probe_seq += [insert_pos]     
    self.slots[insert_pos] = key     
    return insert_pos

二次方:

class BasicHashTable:
def __init__(self,size=7):
    self.size = size
    self.slots = [None] * self.size

def hash_function(self, key):
    return key%len(self.slots)

def rehash(self, old_pos):
    return (old_pos + 1) % self.size

def put(self, key):
    hash_value = key%len(self.slots)    
    probe_seq = []     
    insert_pos = hash_value     
    probe_seq += [insert_pos]     
    probes = 1     
    while(self.slots[insert_pos] != None):         
        insert_pos=(hash_value+probes**2)%len(self.slots)         
        probes+=1        
        probe_seq += [insert_pos]     
    self.slots[insert_pos] = key     
    return insert_pos

现在我要求使用以下方法实现双哈希:"双哈希的hash2函数应该是:hash2(key)= 5 - key%5"

任何人都可以向我解释hash2函数的含义吗?我只是写一个函数吗?

def hash2(key):

如果不是,我将如何回答这个问题?

测试:

hash_t = BasicHashTable()
hash_t.put(3)
hash_t.put(20)
hash_t.put(10)
print(hash_t.slots)

给出:[无,10,无,3,无,无,20]

由于

0 个答案:

没有答案