除留取余法
- 哈希表索引 = 数值 % 哈希表的长度 ;
- 遇到碰撞问题:线性探测法;
- 线性探测法:哈希表存储了数据就重新寻找数据索引存储数据;
- 线形探测公式:哈希表索引= ( 哈希表索引 + 1) % 哈希表长度;
- 除留取余法:通过将数据和哈希表长度比较获取索引位置;
代码
def Hash_Table(num, hash_table):
hash_index = num % len(hash_table)
while True:
if hash_table[hash_index] == "0":
hash_table[hash_index] = num
break
else:
hash_index = (hash_index + 1) % len(hash_table)
if __name__ == '__main__':
data_all = [12, 65, 70, 99, 33, 67, 48]
hash_tables = ["0"] * 13
for i in range(len(data_all)):
Hash_Table(data_all[i], hash_tables)
print(hash_tables)