Python 如何访问hashmap中的溢出列表?
我正在为一个data structures类开发一个hashmap程序,并且已经实现了一个溢出链表,如果数组中的点已经被占用,它将存储一个键、值对。我试图解决setitem方法,并将其从psuedo代码转换为pythonPython 如何访问hashmap中的溢出列表?,python,hashmap,chaining,Python,Hashmap,Chaining,我正在为一个data structures类开发一个hashmap程序,并且已经实现了一个溢出链表,如果数组中的点已经被占用,它将存储一个键、值对。我试图解决setitem方法,并将其从psuedo代码转换为python from Array import * from OList import * class MyMap: def __init__(self, size): self.array = Array(size) self.size = si
from Array import *
from OList import *
class MyMap:
def __init__(self, size):
self.array = Array(size)
self.size = size
self.numsearches = 0
self.numcompares = 0
self.debug = False
def gethash(self, string):
''' The algorithm is to take the ASCII value of each character and multiply it by
the position in the string where the positions start at 1 (not 0). This prevents
transposition collisions.
'''
hashnumber = sum([(i+1)*ord(string[i]) for i in range(0,len(string))]) % self.size
if self.debug: print("gethash(" + string + ")=" + str(hashnumber))
return hashnumber
def _occupied(self, index):
''' This is a private method, that's why its name starts with underscore. '''
return self.array[index] is not None
def __setitem__(self, key,value): # CHANGES IN THIS METHOD (see below)
if self.debug:
print("__setting__ " + key + " = " + value)
index = self.gethash(key)
if self._occupied(index):
if self.debug:
if key == '***':
pass
# if the slot's key is "***" then
# see if the key is in the OList
# if so, then update the value for that node
# else
# put the new key/value into the main slot and leave the OList alone
# else if the slot is None, then put the key/value pair into the main array slot
# else the key may be in the OList
# so just call OList.updateOrAppend(key,value)
# (12 lines of code)
else:
self.array[index] = [key, value, OList()]
我不需要整个方法,我只需要知道我将如何看到关键是否在OList中。
我省略了一些与解决这个问题无关的OList方法,因为OList是一个冗长的模块。
OList模块如下所示:
class OList:
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
def __str__(self):
return "key:" + self.key +" value:" + self.value
def __init__(self):
self.head = None
self.tail = None
def append(self, key, value):
newnode = OList.Node(key, value)
if self.head is None:
self.head = newnode
self.tail = newnode
else:
self.tail.next = newnode
self.tail = newnode
def find(self, key):
count = 0
runner = self.head
while runner != None:
count += 1
if runner.key == key:
return (count,runner)
runner = runner.next
else:
return (count, None)
def updateOrAppend(self, key, value):
count, thenode = self.find(key)
if thenode == None:
self.append(key, value)
else:
thenode.value = value