散列
区块链
散列函数设计
、
def hash(astring, tablesize):
sum = 0
for pos in range(len(astring)):
sum = sum + ord(astring[pos])
return sum%tablesize
映射
H = HashTable()
H[54]='cat'
H[26]='dog'
H[93]='lion'
H[17]='tiger'
H[77]='bird'
H[31]='cow'
H[44]='goat'
H[55]='pig'
H[20]='chiken'
print(H.slots)
print(H.data)
print(H[20])
print(H[17])
H[20] = 'duck'
print(H[20])
print(H[99])
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def hashfuction(self,key): # 简单求余方法来实现散列函数
return key%self.size
def rehash(self,oldhash): # 冲突解决采用线性探测“加1”再散列函数
return (oldhash + 1) % self.size
def put(self, key, data):
hashvalue = self.hashfuction(key)
if self.slots[hashvalue] == None: # key不存在,未冲突
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key: # key已存在,替换
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue) # 散列冲突,再散列,直到找到空槽或者key
while self.slots[nextslot] != None and \
self.slots[nextslot] != key:
nextslot = self.rehash(nextslot)
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def get(self,key):
startslot = self.hashfuction(key) # 标记散列值为查找起点
data = None
stop = False
found = False
position = startslot
# 找key,直到找到空槽或回到起点
while self.slots[position] != None and
not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else: # 未找到key,再散列继续找
position = self.rehash(position)
if position == startslot:
stop = True # 回到起点,停
return data
def __getitem__(self,key):
return self.get(key)
def __setitem(self,key,data):
self.put(key,data)