1 Star 0 Fork 0

Adachi / 2021Besti信安

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
hashtable.py 1.97 KB
一键复制 编辑 原始数据 按行查看 历史
#coding=utf-8
#哈希表(散列表)
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
#简单散列函数
def hashTable(self, key, size):
return key % size
#简单处理哈希冲突
def rehash(self, oldhash, size):
return (oldhash + 1) % size
#插入
def insert(self, key, data):
hashvalue = self.hashTable(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot, len(self.slots))
print('while nextslot:', nextslot)
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
#查找
def search(self, key):
start = self.hashTable(key, len(self.slots))
data = None
stop = False
found = False
position = start
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == start:
stop = True
return data
def __setitem__(self, key, data):
print("key: ",key)
print("data: ",data)
self.insert(key, data)
H=HashTable()
H[54]='cat'
H[54]='kat'
H[65]='mat'
H[76]='rat'
1
https://gitee.com/chen-xialin/cxl20211413.git
git@gitee.com:chen-xialin/cxl20211413.git
chen-xialin
cxl20211413
2021Besti信安
master

搜索帮助